gpt4 book ai didi

c# - 将匿名委托(delegate)传递给线程......为什么这样做有效?

转载 作者:太空狗 更新时间:2023-10-29 20:59:56 24 4
gpt4 key购买 nike

在我的程序中,我们将需要跨四个线程查看的大量数据拆分。

Thread one = new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[0], param2, param3, param4, param5); });
Thread two = new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[1], param2, param3, param4, param5); });
Thread three = new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[2], param2, param3, param4, param5); });
Thread four= new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[3], param2, param3, param4, param5); });

我们的编码标准要求我们符合 StyleCop,可以说,StyleCop 要求如下:

SA1410: Remove the parenthesis from the anonymous method, since the delegate's parameter list is empty.

这样做会给我这个编译器错误:

The call is ambiguous between the following methods or properties: 'System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)' and 'System.Threading.Thread.Thread(System.Threading.ThreadStart)'

我查看了 ThreadStart 和 ParameterizedThreadStart 对象,但我无法弄清楚如何使用这些对象中的任何一个来完成我需要完成的工作。

我的问题:匿名代表如何运作?他们编译成什么?最后,我将不得不在没有匿名代表的情况下完成这项工作,但我不知道从哪里开始。

感谢您的帮助,

探索者

最佳答案

你有两个选择:

  • 忽略 StyleCop 警告(推荐)
  • 将其更改为 new ThreadStart(delegate { ... })

说明:

不带括号的匿名方法 (delegate { ... }) 有一个隐式参数列表。编译器会给它任何需要的参数来匹配它被用作的委托(delegate)。 (你的代码看不到参数)
这在编写不使用其参数的匿名事件处理程序时非常有用;它使您免于键入 delegate(object sender, EventArgs e) { ... }

但是,当调用 Thread 构造函数时,有两种不同的重载需要两种委托(delegate)。
编译器无法知道您要创建的委托(delegate)类型,因为您没有指定参数列表。

关于c# - 将匿名委托(delegate)传递给线程......为什么这样做有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4318451/

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