【发布时间】:2010-12-22 20:57:49
【问题描述】:
我尝试了几个小时来实现这样的场景,但使用输入参数和返回值。
这很好,我得到了我的期望:
public class AsyncStuff2
{
public void DoAsyncStuff()
{
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task myTask = Task.Factory.StartNew(() =>
{
OperationXy();
});
bool hadError = false;
myTask = myTask.ContinueWith(errorTest =>
{
Console.WriteLine("Faulted");
hadError = true;
if (errorTest.Exception != null)
{
Console.WriteLine(errorTest.Exception.Message);
}
}, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiScheduler);
myTask.ContinueWith(another =>
{
Console.WriteLine("Done");
if (hadError)
{
Console.WriteLine("...but with error");
}
}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, uiScheduler);
}
private void OperationXy()
{
Console.WriteLine("OperationXY");
throw new ArgumentException("Just for Test");
}
输出将是这样的:
操作XY 故障 发生一个或多个错误。 完毕 ...但有错误
但是当我修改这个例子时,任务继续不能像我一样工作,除了:
public class AsyncStuff
{
public string Path { get; set; }
public void DoAsyncStuff()
{
Path = "A Input...";
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task<string> myTask = Task<string>.Factory.StartNew((input) =>
{
return OperationXy(Path);
}, Path, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
bool hadError = false;
myTask = myTask.ContinueWith<string>(errorTest =>
{
Console.WriteLine("Faulted");
hadError = true;
if (errorTest.Exception != null)
{
Console.WriteLine(errorTest.Exception.Message);
}
return null;
}, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiScheduler);
myTask.ContinueWith(another =>
{
Console.WriteLine("Done, Result: {0}", myTask.Result);
if (hadError)
{
Console.WriteLine("...but with error");
}
}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, uiScheduler);
}
private string OperationXy(string returnThat)
{
Console.WriteLine("OperationXY, Input ({0})", returnThat);
//throw new ArgumentException("Just for Test");
return returnThat;
}
}
我想要实现的是:
- 将处理所需的输入传递给任务
- 将结果设置为 UI 元素
- 处理错误,但仍继续“OnlyOnRanToCompletion”
任何帮助表示赞赏
谢谢
马丁
【问题讨论】:
标签: c# task parallel-processing task-parallel-library