Home > Net >  Closing MessageBox in separate thread after parallel process is done
Closing MessageBox in separate thread after parallel process is done

Time:05-26

I'm writing a program that, when started, will open a WPF window which has a couple of time-consuming tasks in its constructor (mostly gathering data from a db).

Opening this WPF window is the very first thing that this program is doing, so, because it takes a couple of seconds to gather the data, you call the program and nothing happens for a couple of seconds and then the window pops up. Therefore I thought I'd add a simple message that pops up in the meantime saying that something's happening in the background.

I tried by putting a MessageBox in a separate thread and then closing the thread when the main process is done, but so far that's not working. My code for the main method is:

        Thread t = new Thread(() => MessageBox.Show("Gathering data..."));
        t.Start();

        // Ui that takes a few seconds to popup
        FileCreationWindow setupWindow = new FileCreationWindow();

        t.Join();

t.Join() doesn't work because it starts popping up a Server Busy error. If I use t.Abort() instead nothing happens (plus I know that that isn't the right way of doing it) and finally, of course, if I don't put anything the MessageBox will stay open.

How do I do this?
I'm also happy to review how I do it if, for example, you guys say that the MessageBox is not the best way. In general I'd prefer something pretty simple that doesn't involve a lot of code and reinventing the wheel.

Thanks!

CodePudding user response:

Using invoke to join curren thread and see answer in the question: Close a MessageBox after several seconds

Invoke(new Action(() =>
            {
                ....
            }));

CodePudding user response:

I actually went for the easiest solution possible, which for some reason I hadn't think of initially. I guess for some reason I got stuck with having to use a separate thread and couldn't see Occam's razor. Here where I landed now:

        WaitDataWindow userNotification = new WaitDataWindow();
        userNotification.Show();

        // Pop ui
        FileCreationWindow setupWindow = new FileCreationWindow();

        userNotification.Close();

Interested in hearing if there are evident weaknesses doing this.

Cheers

CodePudding user response:

You can use the async await, or may use semaphore for waiting for the thread to complete.

public async static Task Main(string[] args)
    {
        var msgBox = new Form();
        Task t = new Task(() => msgBox.ShowDialog());
        t.Start();
        await Program.DataProcessor();
        Task.WaitAll();
        

    }
    public static async Task<bool> DataProcessor()
    {
        Thread.Sleep(2000);
        Console.WriteLine("done with data");
        return true;
    }
  •  Tags:  
  • c#
  • Related