gpt4 book ai didi

c# - 如何从一个对象启动两个并行线程?

转载 作者:行者123 更新时间:2023-11-30 22:58:40 25 4
gpt4 key购买 nike

假设我有一个对象,它有一个持续运行的方法。我已经创建了一个运行此方法的新线程:

new Thread(new ThreadStart(myObject.firstMethod)).Start();

现在,我在 myObject 中有一个要启动的 secondMethod。请记住,先前启动的线程不会终止,因为 firstMethod 包含一个循环。

如何启动第二种方法?我需要创建第二个线程吗?

最佳答案

有点不清楚你在问什么或你到底想达到什么目的,但是这里有一个使用 Task 的例子运行 2 个无限循环(直到调用取消标记)

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();
}

Demo Here


Task vs Thread differences

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.

报价 Jon Skeet

关于c# - 如何从一个对象启动两个并行线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com