【发布时间】:2015-10-06 14:03:24
【问题描述】:
请帮助我找到正确的解决方案。 主要问题是通过控制台等待程序完成,同时监控任务。
我写了一些原型,但我不确定它是否有效——在这种方法中,我们花费了一个额外的线程来等待来自控制台的操作。我没有看到替代品,因为 Console 不支持异步(某种 Console.ReadLineAsync)。
更新: 我有两个工作任务(task1、task2)。它们模拟了一些实际工作。 该程序是一个控制台。所以我们需要给用户一个停止程序的机会。默认情况下,在控制台中,这是通过按“Enter”完成的(通过consoleTask)。
问题是。如何等待工作线程完成并监控用户的停止命令。
static void Main(string[] args)
{
CancellationTokenSource mycts = new CancellationTokenSource();
var task1 = Task.Run(() =>
{
// doing some work, that can throw exception
Thread.Sleep(1000);
// how to avoid this closuring ?
mycts.Token.ThrowIfCancellationRequested();
throw new InvalidOperationException("test");
}).ContinueWith((_) => mycts.Cancel()); // Do I need caching this task?
var task2 = Task.Run(() =>
{
// doing some work, that can throw exception
Thread.Sleep(5000);
// again closuring
mycts.Token.ThrowIfCancellationRequested();
throw new InvalidOperationException("test");
}).ContinueWith((_) => mycts.Cancel()); // Do I need caching this task?
// I do not know how to do better with Console !!
var consoleTask = Task.Factory.StartNew((cts) =>
{
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}, mycts).ContinueWith((_) => mycts.Cancel()); // Do I need caching this task?
// Waiting for the Completion or Exception
Task.WaitAny(task1, task2, consoleTask);
// Now waiting for the completion of workflow
try
{
Task.WaitAll(task1, task2);
}
catch (Exception ex)
{
// log faulted tasks
}
//Exit
}
【问题讨论】:
-
你不应该有
Task.WaitAll(task1, task2);,因为如果WaitAny因为异常而返回,那么你将需要按回车键退出。 (它会让你像疯了一样敲回车,以防万一有异常被默默抛出) -
真的吗?我预计在异常处理块之后,程序将正确完成。嗯
-
它将正确完成,但您明确要求结束所有任务。虽然我没有尝试过,但这就是它的样子。我可能错了
标签: c# .net asynchronous console task-parallel-library