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

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

    Ok, I'm unsure of how you want to go about this. From your example, it looks like WorkerMethod does not create its own thread to execute under, but you want to call that method on another thread.

    In that case, create a short worker method that calls WorkerMethod then calls SomeOtherMethod, and queue that method up on another thread. Then when WorkerMethod completes, SomeOtherMethod is called. For example:

    public class AClass
    {
        public void SomeMethod()
        {
            DoSomething();
    
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                BClass.WorkerMethod();
                SomeOtherMethod();
            });
    
            DoSomethingElse();
        }
    
        private void SomeOtherMethod()
        {
            // handle the fact that WorkerMethod has completed. 
            // Note that this is called on the Worker Thread, not
            // the main thread.
        }
    }
    

提交回复
热议问题