And*_*man 0 .net c# multithreading task
我学习以书本为基础的线程。
我想等待我的任务及其继续进行。但是我在“ BLEEEEEEEEEEEEEEEP ” 之前看到“按任意键退出... ”消息(请查看我的代码注释)。为什么会发生,如何解决?
我知道我可以使用两个任务并将其Task.Wait()用于每个任务,但是如果我需要对延续对象执行相同的操作怎么办?
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Bushman.Sandbox.Threads {
class Program {
static void Main(string[] args) {
Console.Title = "Threads";
try {
// The main work
Action act1 = () => {
for (int i = 0; i < 10; i++) {
int id = Thread.CurrentThread
.ManagedThreadId;
Console.WriteLine(
"bleep. Thread Id: {0}",
id.ToString());
}
};
// This operation is to be done when the main
// work will be finished.
Action act2 = () => {
int id = Thread.CurrentThread
.ManagedThreadId;
Console.WriteLine(
"bleep. Thread Id: {0}",
id.ToString());
Console.WriteLine(
"BLEEEEEEEEEEEEEEEP. Thread Id: {0}",
id.ToString());
};
Task task = new Task(act1);
var awaiter = task.GetAwaiter();
awaiter.OnCompleted(act2);
Console.WriteLine("Work started...");
task.Start();
// TODO: wait while both actions will be done
task.Wait(); // it doesn't work as I expected
// it doesn't work as I expected too...
awaiter.GetResult();
}
catch (Exception ex) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
Console.WriteLine("Press any key for exit...");
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
OnCompleted事件是在您不等待的其他线程上触发的。您可以使用以下构造:
Task task = new Task(act1);
var awaiter = task.ContinueWith(x => act2()).GetAwaiter();
task.Start();
Console.WriteLine("Work started...");
awaiter.GetResult();
Run Code Online (Sandbox Code Playgroud)
在这种情况下,act1将使用第一个任务执行该任务,当该任务完成时,它将继续执行act2。在这种情况下,等待者将等待两者均完成。
| 归档时间: |
|
| 查看次数: |
684 次 |
| 最近记录: |