假设我有一个对象,它有一个不断运行的方法。 我已经创建了一个运行此方法的新线程:
new Thread(new ThreadStart(myObject.firstMethod)).Start();
现在,我想在 myObject
中启动一个 secondMethod
。
请记住,之前启动的线程不会终止,因为 firstMethod
包含循环。
如何启动第二种方法?我需要创建第二个线程吗?
最佳答案
不太清楚您在问什么或您到底想要实现什么,但是这里有一个使用 Task
的示例运行 2 个无限循环(直到调用取消 token )
public static void Method1(CancellationToken token)
{
Task.Run(
async () =>
{
while (!token.IsCancellationRequested)
{
// do something
await Task.Delay(500, token); // <- await with cancellation
Console.WriteLine("Method1");
}
}, token);
}
public static void Method2(CancellationToken token)
{
Task.Run(
async () =>
{
while (!token.IsCancellationRequested)
{
// do something
await Task.Delay(300, token); // <- await with cancellation
Console.WriteLine("Method2");
}
}, token);
}
private static void Main(string[] args)
{
var source = new CancellationTokenSource();
Method1(source.Token);
Method2(source.Token);
source.CancelAfter(3000);
Console.ReadKey();
}
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the future- A task returned by
WebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)- A task returned by
Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.Note that the
Task<T>
abstraction is pivotal to the async support in C# 5.In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
关于c# - 如何从一个对象启动两个并行线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888395/