[英]How to keep a thread running and not terminate when a function finishes
我有这个线程,我不希望它在完成功能后自行终止。 相反,我想在此后给它另一个功能。 `
t1 = new Thread(() => test());
t1.Start();
if(t1 finished the task )
{
give t1 new task for exmp test2
}
如果使用的是.Net 4或更高版本,则可以使用Task
而不是线程,然后可以使用Task.ContinueWith()
实现此功能。
这是一个例子:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
static class Program
{
private static void Main()
{
var task = Task.Run(() => task1());
task = task.ContinueWith(antecedant => task2());
Console.WriteLine("Waiting for composite task to complete.");
task.Wait();
Console.WriteLine("Composite Task completed.");
}
private static void task1()
{
Console.WriteLine("Starting task 1");
Thread.Sleep(2000);
Console.WriteLine("Ending task 1");
}
private static void task2()
{
Console.WriteLine("Starting task 2");
Thread.Sleep(2000);
Console.WriteLine("Ending task 2");
}
}
}
如果使用此方法,则无需等待第一个任务完成就可以将其分配给另一个任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.