Делегирование задачи и получение уведомления о ее завершении (в C#)

концептуально я хотел бы выполнить следующее, Но у меня возникли проблемы с пониманием того, как правильно кодировать его в C#:


SomeMethod { // Member of AClass{}
    DoSomething;
    Start WorkerMethod() from BClass in another thread;
    DoSomethingElse;
}

затем, когда WorkerMethod() выполните это:


void SomeOtherMethod()  // Also member of AClass{}
{ ... }

может кто-нибудь привести пример?

7 ответов


на BackgroundWorker класс был добавлен в .NET 2.0 именно для этой цели.

в двух словах вы:

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

вы также можете добавить причудливые вещи, такие как отмена и отчет о ходе работы, если хотите:)


в .Net 2 был представлен BackgroundWorker, что упрощает выполнение асинхронных операций:

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();

в .Net 1 Вы должны использовать потоки.


вы должны использовать AsyncCallBacks. Можно использовать AsyncCallBacks для указания делегата метода, а затем указать методы обратного вызова, которые вызываются после завершения выполнения целевого метода.

вот небольшой пример, запустите и посмотрите сами.

программы класс {

    public delegate void AsyncMethodCaller();


    public static void WorkerMethod()
    {
        Console.WriteLine("I am the first method that is called.");
        Thread.Sleep(5000);
        Console.WriteLine("Exiting from WorkerMethod.");
    }

    public static void SomeOtherMethod(IAsyncResult result)
    {
        Console.WriteLine("I am called after the Worker Method completes.");
    }



    static void Main(string[] args)
    {
        AsyncMethodCaller asyncCaller = new AsyncMethodCaller(WorkerMethod);
        AsyncCallback callBack = new AsyncCallback(SomeOtherMethod);
        IAsyncResult result = asyncCaller.BeginInvoke(callBack, null);
        Console.WriteLine("Worker method has been called.");
        Console.WriteLine("Waiting for all invocations to complete.");
        Console.Read();

    }
}

хотя здесь есть несколько возможностей, я бы использовал делегат, асинхронно называемый using BeginInvoke метод.

предупреждение : Не забудьте всегда звонить EndInvoke на IAsyncResult чтобы избежать возможных утечек памяти, как описано в в этой статье.


Проверьте BackgroundWorker.


Использовать Асинхронные Делегаты:

// Method that does the real work
public int SomeMethod(int someInput)
{
Thread.Sleep(20);
Console.WriteLine(”Processed input : {0}”,someInput);
return someInput+1;
} 


// Method that will be called after work is complete
public void EndSomeOtherMethod(IAsyncResult result)
{
SomeMethodDelegate myDelegate = result.AsyncState as SomeMethodDelegate;
// obtain the result
int resultVal = myDelegate.EndInvoke(result);
Console.WriteLine(”Returned output : {0}”,resultVal);
}

// Define a delegate
delegate int SomeMethodDelegate(int someInput);
SomeMethodDelegate someMethodDelegate = SomeMethod;

// Call the method that does the real work
// Give the method name that must be called once the work is completed.
someMethodDelegate.BeginInvoke(10, // Input parameter to SomeMethod()
EndSomeOtherMethod, // Callback Method
someMethodDelegate); // AsyncState

хорошо, я не уверен, как вы хотите это сделать. Из вашего примера похоже, что WorkerMethod не создает свой собственный поток для выполнения, но вы хотите вызвать этот метод в другом потоке.

в этом случае создайте короткий рабочий метод, который вызывает WorkerMethod, затем вызывает SomeOtherMethod и очередь этого метода в другом потоке. Затем, когда WorkerMethod завершается, вызывается SomeOtherMethod. Например:

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.
    }
}