C#.net - How to alert program that the thread is finished (event driven)?

37,054

Solution 1

What you want to do -- wait for the background thread in a method of the UI thread but still allow the UI to be responsive -- is not possible. You need to split your code into two parts: One executed before starting (or parallel to) the background thread and the other one running after the background thread has finished.

The easiest way is to use the BackgroundWorker class. It raises an event in the UI thread (RunWorkerCompleted) after its work is done. Here's an example:

public void start()
{
    var bw = new BackgroundWorker();

    // define the event handlers
    bw.DoWork += (sender, args) => {
        // do your lengthy stuff here -- this will happen in a separate thread
        ...
    };
    bw.RunWorkerCompleted += (sender, args) => {
        if (args.Error != null)  // if an exception occurred during DoWork,
            MessageBox.Show(args.Error.ToString());  // do your error handling here

        // Do whatever else you want to do after the work completed.
        // This happens in the main UI thread.
        ...
    };

    bw.RunWorkerAsync(); // starts the background worker

    // execution continues here in parallel to the background worker
}

Solution 2

Just raise an event. It will run on the wrong thread so whatever event handler has to deal with that by marshaling the call if necessary to update any UI. By using Control.Begin/Invoke or Dispatcher.Begin/Invoke, depending what class library you use.

Or use the BackgroundWorker class, it does it automatically.

Share:
37,054
unknownNewbie
Author by

unknownNewbie

Updated on February 28, 2020

Comments

  • unknownNewbie
    unknownNewbie about 4 years

    this is a snippet from my class:

    public bool start()
    {
       Thread startThread = new Thread(this.ThreadDealer);
       startThread.Start();
       return _start;
    }
    

    In ThreadDealer() I'm setting the boolean variable "_start" to false or true. What I need now but can't seem to figure out is an event to alert start() to execute its return statement when the ThreadDealer()-Thread has finished.

    I tried something with an AutoResetEvent and .WaitOne() but since I have a GUI that just blocks everything and while it does what I need it to do (wait for the Thread to finish) it is useless if it blocks my GUI.

    Any help would be much appreciated.