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

标签 c# multithreading

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

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

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/

相关文章:

c# Regex.Match 与 .Net Regex Tester 结果不匹配

c# - EF在急切加载和延迟加载方面的区别?

java - 如何阻止两个线程对象访问来自同一类的 1 个方法

c# - 对多个文件副本使用多线程

java - 暂停线程以防止 ConcurrentModificationException?

java - 原子变量是否保证内存可见性?

python - 来自 tkinter 应用程序的多线程

c# - 如何配置位图源

c# - ASP.NET MVC View 未接收传递给它的列表

c# - 没有回发的级联下拉列表