【发布时间】:2017-01-10 09:37:33
【问题描述】:
我创造了作品链。他们将在我的附加线程中工作。为此,我使用Task。另外,如果发生任何异常,我想中断链的工作并将其抛出到调用线程中。但我看到我的链没有断,act2 和act3 也完成了。
我该如何解决?
using System;
using System.Threading.Tasks;
namespace Bushman.Sandbox.Threads {
class Program {
static void Main(string[] args) {
Console.Title = "Custom thread";
try {
// First work
Action act1 = () => {
for (int i = 0; i < 5; i++) {
// I throw the exeption here
if (i == 3) throw new Exception("Oops!!!");
Console.WriteLine("Do first work");
}
};
// Second work
Action act2 = () => {
for (int i = 0; i < 5; i++)
Console.WriteLine(" Do second work");
};
// Third work
Func<int> act3 = () => {
for (int i = 0; i < 5; i++)
Console.WriteLine(" Do third work");
return 12345;
};
Task task = new Task(act1);
// Build the chain of the works
var awaiter = task.ContinueWith(_ => act2(),
TaskContinuationOptions.ExecuteSynchronously)
.ContinueWith(_ => act3(),
TaskContinuationOptions.ExecuteSynchronously)
.GetAwaiter();
Console.WriteLine("Work started...");
// launch the chain
task.Start();
// Here I get some result
int result = awaiter.GetResult(); // 12345
if (task.IsCanceled || task.IsFaulted) {
throw task.Exception.InnerException;
}
Console.WriteLine("The result: {0}",
result.ToString());
}
catch (Exception ex) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
Console.WriteLine("Press any key for exit...");
Console.ReadKey();
}
}
}
【问题讨论】:
-
你为什么不直接使用
async/await?您也不需要Task.Start或直接访问等待者。此外,如果您想使用ContinueWith,您需要访问任务以检查异常,例如 -ContinueWith(t => if (t.Faulted) {..} else act3();) -
我通过一本书学会了使用线程\任务。我还没有读到
async/await。 -
如果您不想使用
async/await,我建议您查看有关如何正确使用的文档示例,例如 ContinueWith 和 TasFactory.StartNew 或 Task.Run。还要检查 Task.Result 和 Task.Wait() 做什么 - 如果任务出错,它们 do 会抛出。您的代码过于复杂,并试图公开它不需要的实现内部
标签: c# .net multithreading task multitasking