Delegating a task in and getting notified when it completes (in C#)

前端 未结 7 886
灰色年华
灰色年华 2020-12-06 18:06

Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:


SomeMethod { // Member of AClass{}
            


        
7条回答
  •  不知归路
    2020-12-06 18:16

    In .Net 2 the BackgroundWorker was introduced, this makes running async operations really easy:

    BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true };
    
    bw.DoWork += (sender, e) => 
       {
           //what happens here must not touch the form
           //as it's in a different thread
       };
    
    bw.ProgressChanged += ( sender, e ) =>
       {
           //update progress bars here
       };
    
    bw.RunWorkerCompleted += (sender, e) => 
       {
           //now you're back in the UI thread you can update the form
           //remember to dispose of bw now
       };
    
    worker.RunWorkerAsync();
    

    In .Net 1 you have to use threads.

提交回复
热议问题