【发布时间】:2015-02-23 22:03:00
【问题描述】:
我有一个班级 Worker 正在做一些工作(模拟工作量):
public class Worker
{ ...
public void DoWork(CancellationToken ct)
{
for (int i = 0; i < 10; i++)
{
ct.ThrowIfCancellationRequested();
Thread.Sleep(2000);
}
}
现在我想在 Task.Run 中使用此方法(来自我的 Windows 窗体应用程序,单击按钮),可以取消:
private CancellationTokenSource _ctSource;
try
{
Task.Run(() =>
{
_worker.DoWork(_ctSource.Token);
},_ctSource.Token);
}
catch (AggregateException aex)
{
String g = aex.Message;
}
catch (OperationCanceledException ex)
{
String g = ex.Message;
}
catch (Exception ex)
{
String g = ex.Message;
}
但是当任务启动时,我不能用_ctSource.Cancel()取消它;
我在 Visual Studio 中收到一个错误,即 OperationCanceledException 未处理!
但是我用 try-catch-clause 包围了 Task.Run 调用! Worker 对象中发生的异常应该抛出还是不抛出?
有什么问题?
【问题讨论】:
-
OperationHandledException?你确定吗?我从来没有听说过这样的事情。 -
我的意思是 OperationCanceledException :-)
-
I get an error in visual studio that the OperationCanceledException is not handled!只需点击F5并忽略它。当你在 VS 之外运行它时,你不会得到它。顺便说一句:您无法像在代码中那样捕获任务的异常。您创建一个任务并退出 try 块。ContinueWith可能会有所帮助。
标签: c# .net exception task-parallel-library