- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个对象,它有一个持续运行的方法。我已经创建了一个运行此方法的新线程:
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();
}
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/
我是一名优秀的程序员,十分优秀!