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

后端 未结 2 1341
南笙
南笙 2020-12-06 03:09

this is a snippet from my class:

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


        
相关标签:
2条回答
  • 2020-12-06 03:21

    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
    }
    
    0 讨论(0)
  • 2020-12-06 03:24

    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.

    0 讨论(0)
提交回复
热议问题