c# - 如何通过lambda表达式获取线程的 "pass in any number of arguments to the method"?

标签 c# multithreading delegates lambda closures

我关注 Passing Data to a Thread约瑟夫·阿尔巴哈里 (Joseph Albahari) 的“C# 线程”的“第 1 部分:入门”。

即段落:

====== 引用开始

使用这种方法,您可以将任意数量的参数传入(到哪里?)该方法。您甚至可以将整个实现包装在一个多语句 lambda 中:

new Thread (() =>  
{  
  Console.WriteLine ("I'm running on another thread!");  
  Console.WriteLine ("This is so easy!");  
}).Start();*  

您可以使用匿名方法在 C# 2.0 中几乎同样轻松地完成同样的事情:

  new Thread (delegate()  
  {  
  ...
  }).Start();

============引用结束

也就是说,我已经“轻松”地尝试过:

new Thread
(delegate
  {
    Console.WriteLine("I'm running on another thread!");
    Console.WriteLine("This is so easy!");
   }
).Start();

但它会产生错误:

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

  1. 如何消除代码歧义以便运行它? 已回答(遗漏括号。无论如何,这不是最初的主要问题)
  2. 另外,我不太明白空列表 () => 指向/应用于哪里?
  3. 还有,“您可以向该方法传递任意数量的参数”的方法是什么?
  4. 如何理解通过空列表传递(任意数量的)参数?

更新(针对 Jon Skeet 的评论):
不,我没有被 C# 2 困住。

the previous passage 相同的问题:

========== 引用开始:
"将参数传递给线程的目标方法的最简单方法是执行一个 lambda 表达式,该表达式使用所需的参数调用该方法:

static void Main()
{
  Thread t = new Thread ( () => Print ("Hello from t!") );
  t.Start();
}

static void Print (string message) 
{
  Console.WriteLine (message);
}

使用这种方法,您可以将任意数量的参数传递给该方法。”

===============引用结束

更新2:
most complete answer is IMO by @Lee尽管我将另一个答案标记为正确,但我猜想立即回答我最初没有问过的问题 - 如何将某些内容放在空括号中(我已经害怕通过列表或参数来调用它)

最佳答案

您需要使参数列表显式:

new Thread
(delegate()
  {
    Console.WriteLine("I'm running on another thread!");
    Console.WriteLine("This is so easy!");
   }
).Start();

delegate 关键字允许您定义一个 anonymous method . Lambda 表达式(即使用 () => { ... } 语法)类似,但是使用 delegate 允许您省略参数列表。在这种情况下这是不明确的,因为 Thread 有两个构造函数,它们采用不同的委托(delegate)类型。一个采用 ThreadStart 定义为

delegate void ThreadStart();

另一个采用 ParameterizedThreadStart 定义为:

delegate void ParameterizedThreadStart(object state);

由于您省略了参数列表,编译器不知道您使用的是哪种委托(delegate)类型。

我假设“任意数量的参数”是由您的委托(delegate)封闭的变量。例如你可以:

string message = "This is so easy!";
var thread = new Thread(delegate() {
    Console.WriteLine(message);
});
thread.Start();

您可以使用 ParameterizedThreadStart 将任意对象传递给您的线程委托(delegate),例如

public class ThreadData {
   //properties to pass to thread
}

ThreadData data = new ThreadData { ... }
Thread thread = new Thread((object state) => {
    ThreadData data = (ThreadData)state;
});

thread.Start(data);

关于c# - 如何通过lambda表达式获取线程的 "pass in any number of arguments to the method"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15024558/

相关文章:

c# - 如何等待 WPF 绑定(bind)延迟完成

c# - DhtmlX 甘特图未获得正确的链接目标 ID

javascript - 无法从 aspx 页面获取下拉选定值到后端

c# - WPF 任务管理器 : Handling Refreshing CPU Load Value?

c# - 工作线程和后台工作线程之间的区别?

iphone - GameCenter 功能崩溃应用程序 - 谁能帮忙解决?

iphone - 错误的委托(delegate)声明

c# - 将二进制文件或 byte[] 从 c# 传递到 java

java - 球不动;线?

iphone - Xcode:委托(delegate)对象是否必须向委托(delegate)对象发送消息?