Csharp/C#教程:以异步方式运行两个任务并等到它们结束的最快方法分享


以异步方式运行两个任务并等到它们结束的最快方法

好的,我需要改变这个..

void foo() { DoSomething(1, 0); DoSomething(2, 3); } 

这样的事……

 void foo() { //this functions is sync.. I need to run them async somehow new Thread(DoSomething(1, 0)); new Thread(DoSomething(2, 3)); //Now I need to wait until both async functions will end WaitUntilBothFunctionsWillEnd(); } 

有没有办法在Silverlight中执行此操作?

 void foo() { var thread1 = new Thread(() => DoSomething(1, 0)); var thread2 = new Thread(() => DoSomething(2, 3)); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); } 

Thread.Join()方法将阻塞执行,直到线程终止,因此加入两个线程将确保foo()仅在两个线程终止后才返回。

 Task task1 = Task.Factory.StartNew( () => {DoSomething(1,0);}); Task task2 = Task.Factory.StartNew( () => {DoSomething(2,3);}); Task.WaitAll(task1,task2); 

您需要将Microsoft Async软件包(及其依赖项)添加到您的silverlight项目中。

尽管像Ralph的回答所提到的TPL在Silverlight中不可用,但我真的很喜欢Task模型……那么为什么不写一个类似的瘦线程包装器。

 using System; using System.Threading; using System.Linq; public class Task { ManualResetEvent _mre = new ManualResetEvent(false); public Task(Action action) { ThreadPool.QueueUserWorkItem((s) => { action(); _mre.Set(); }); } public static void WaitAll(params Task[] tasks) { WaitHandle.WaitAll(tasks.Select(t => t._mre).ToArray()); } } 

那么你可以像TPL一样使用它:

 int param1 = 1; int param2 = 2; Task.WaitAll( new Task( () => DoSomething(param1, param2) ), new Task( () => DoSomething(param1, param2) ) ); 

在封面下,这使得ThreadPool的责任是将系统中的线程限制为合理的计数。

上述就是C#学习教程:以异步方式运行两个任务并等到它们结束的最快方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1012568.html

(1)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐