Dim*_*ima 5 .net c# delegates asynchronous
我需要为同一个函数调用异步数量的委托.问题是我应该如何对待回调功能?我们有几个代理运行,所以CallbackMethod并不意味着所有异步委托都完成了.
AsyncMethodCaller c = new AsyncMethodCaller(instance.dummyMethod);
for (int i = 0; i < 100; i++)
{
IAsyncResult res = c.BeginInvoke(5000,
out dummy,
new AsyncCallback(CallbackMethod),
"executed on thread {0}, with result value \"{1}\".");
}
Run Code Online (Sandbox Code Playgroud)
我会考虑使用TPLTask提供的 s 。
var task1 = Task.Run(() => instance.dummyMethod)
.ContinueWith((completedTask) => Console.WriteLine("Each callback here. Result: " + completedTask.Result));
// Blocks calling thread until all tasks are done.
Task.WaitAll(new [] { task1, task2 });
Run Code Online (Sandbox Code Playgroud)
allWaitAll确保Task在继续主线程之前完成所有操作。上面允许您实现单独的回调。
或者,当所有异步方法完成时,使用单个回调:
Task.Factory.ContinueWhenAll(new [] { task1, task2 },
(allTasks) => Console.WriteLine("Callback when all are done."));
Run Code Online (Sandbox Code Playgroud)