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

前端 未结 7 893
灰色年华
灰色年华 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:24

    The BackgroundWorker class was added to .NET 2.0 for this exact purpose.

    In a nutshell you do:

    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += delegate { myBClass.DoHardWork(); }
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);
    worker.RunWorkerAsync();
    

    You can also add fancy stuff like cancellation and progress reporting if you want :)

提交回复
热议问题