【发布时间】:2014-07-29 20:26:30
【问题描述】:
所以我仍在尝试理解 async/await 模式,但我也在尝试实现以下行为:
方法 A 调用方法 B,该方法运行多个进程。其中一些进程可以在单独的线程上运行,而其他事情正在处理,以便它们的返回值将在更接近需要时可用。在所有这些过程完成之前,方法 B 不需要将控制权返回给调用者。
这是我正在使用的测试代码:
static void Main(string[] args)
{
CallProc();
Console.WriteLine("Program finished");
Console.ReadKey();
}
public static async Task CallProc()
{
var two = Task.Factory.StartNew(() => SomeSynchronousProcessIDontOwn(5000, "two"));
var one = Task.Factory.StartNew(() => SomeSynchronousProcessIDontOwn(500, "one"));
var three = Task.Factory.StartNew(() => SomeSynchronousProcessIDontOwn(1500, "three"));
// some process happens here
var oneMessage = await one; // waits until one finishes and then snags it's value
Console.WriteLine("Got message {0}", oneMessage);
// some more stuff happens here
var twoMessage = await two; // waits until two is finished and then snags it's value
Console.WriteLine(twoMessage);
// TODO: need to make sure that everything is completed before returning control to caller
}
public static string SomeSynchronousProcessIDontOwn(int delayTime, string message, bool delay = true)
{
Console.WriteLine("Starting \"{0}\"", message);
if(delay) Thread.Sleep(delayTime);
return string.Format("Finished \"{0}\"", message);
}
现在,发生的事情是,除了方法在所有内容完成之前返回之外,所有内容都符合我的预期,因此输出显示“程序完成”,而“两个”仍在运行。
我该如何写,以便CallProc() 可以异步执行这些任务,但延迟返回,直到一切都完成。也就是说CallProc()需要异步运行一些任务,而CallProc()本身需要同步调用。
【问题讨论】:
-
您是否尝试过使用 Task 集合并使用 Task.WaitAll() 方法?
-
我做到了。它产生了相同的结果。控制权在一切完成之前返回给 main()
-
你为什么不把
await three也放在最后呢? -
我不会建议这个作为答案,因为我没有信心,但你不只是想要 CallProc().Wait();确实和 James 的回答一样,但是 CallProc 仍然可以异步调用。
-
@Hammerstein 这是我使用
WhenAll的意图,CallProc的想法可以在外部等待。
标签: c# .net multithreading asynchronous async-await