【问题标题】:Difference in initialization of Threads .NETThreads .NET 初始化的差异
【发布时间】:2023-01-10 20:10:25
【问题描述】:

线程的后续初始化和我应该何时使用它们之间有什么区别?

Printer printer = new Printer();
Thread thread = new Thread(new ThreadStart(printer.Print0));
Thread thread2 = new Thread(printer.Print0);
Thread thread3 = new Thread(() => printer.Print0());

【问题讨论】:

  • 在所有情况下都使用相同的构造函数。尽管 Thread(ThreadStart) 构造函数调用的委托以不同的方式指定,1) 显式指定,2) 作为方法组和 3) 作为调用 Print0 的 lambda。
  • 谢谢。使用显式调用和 lambda 表达式有什么好处吗?

标签: .net multithreading


【解决方案1】:

System.Threading.Thread 类有 the constructors

public class Thread
{
    public Thread (System.Threading.ThreadStart start);
}

为什么 System.Threading.ThreadStart startdelegate

public delegate void ThreadStart();

实例化委托的语法是:

ThreadStart myDelegate = new ThreadStart(printer.Print0);

// C#2 add this sugar syntax, but it's same instruction that below
ThreadStart myDelegate = printer.Print0;

那么这个语法是等价的:

Thread thread = new Thread(new ThreadStart(printer.Print0));
Thread thread2 = new Thread(printer.Print0);

只是第二次在 C#2 中使用糖语法添加。


在 C#3 中,lambda 以一种新的方式添加到语言中来声明委托:

ThreadStart myDelegate = () => { printer.Print0 };

就像是 :

public class MyLambda
{
    public Printer printer;

    void Run()
    {
        printer.Print0();
    }
}

ThreadStart myDelegate = new MyLambda() { printer = printer }.Run;

不完全像第一个例子,因为从技术上讲它调用了一个中间方法。但唯一的感知差异是调用堆栈......我认为这种语法相似。


从您的评论中回答您的问题:

使用显式调用和 lambda 表达式有什么好处吗?

不,这只是不同的语法。您可以选择您喜欢的一个而无需其他考虑。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多