将参数传递给线程
我想传递一个函数,该函数将参数传递给C#中的ThreadStart构造函数。 但是,似乎这是不可能的,因为我得到一个语法错误,我尝试做这样的事情
Thread t1 = new Thread(new ThreadStart(func1(obj1));
其中obj1是List
类型的对象(比如说)。
如果我想要一个线程来执行这个接受一个对象作为参数的函数,并且我打算用不同的参数值同时创建2个这样的线程,那么实现这个的最佳方法是什么?
您需要ParametrizedThreadStart
将参数传递给线程。
Thread t1 = new Thread(new ParametrizedThreadStart(func1); t1.Start(obj1);
如果您使用的是.NET 3.5或更高版本,则可以选择使用lambda:
var myThread = new System.Threading.Thread(() => func1(obj1));
你可以像这样开始一个新的线程:
Thread thread = new Thread(delegate() { // Code here. }); thread.Start();
在匿名方法中,您可以访问创建委托时范围内的变量。
试试这个:
var bar = 0.0; Thread t = new Thread(() => { Foo(bar); }); t.IsBackground = true; t.Start();
或者在你的情况下:
Object obj1 = new Object(); Thread t = new Thread(() => { func1(obj1); }); t.IsBackground = true; t.Start();
这是你正在寻找的效果吗?
static void Main(string[] args) { var list = new List(){ "a","b","c" }; Thread t1 = new Thread(new ParameterizedThreadStart(DoWork)); t1.Start(list); Console.ReadLine(); } public static void DoWork(object stuff) { foreach (var item in stuff as List ) { Console.WriteLine(item); } }
编辑刺客无法使此代码生效,因此我在本文末尾包含了一个完整的示例控制台应用程序。
{ // some code Thread t1 = new Thread(MyThreadStart); t1.Start(theList); } void MyThreadStart(object state) { List
theList = (List )state; //.. } { // some code Thread t1 = new Thread(MyThreadStart); t1.Start(theList); } void MyThreadStart(object state) { List
theList = (List )state; //.. }
这是我的编辑:下面是一个完整的控制台应用程序 – 该技术确实有效:
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { System.Threading.Thread t = new System.Threading.Thread(MyThreadStart); t.Start("Hello"); System.Console.ReadLine(); } static void MyThreadStart(object state) { System.Console.WriteLine((string)state); } } }
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { System.Threading.Thread t = new System.Threading.Thread(MyThreadStart); t.Start("Hello"); System.Console.ReadLine(); } static void MyThreadStart(object state) { System.Console.WriteLine((string)state); } } }
static void func1(object parameter) { // Do stuff here. } static void Main(string[] args) { List obj1 = new List (); Thread t1 = new Thread(func1); t1.Start(obj1); }
它在.Net 2.0中使用名为ParameterizedThreadStart的新委托。 你可以在这里阅读它。
请参见ParameterizedThreadStart
你绝对需要使用Thread
对象吗? 或者您只是在寻找multithreading处理? 更“现代”的方法是使用异步委托:
private delegate void FuncDelegate(object obj1); . . . FuncDelegate func = func1; IAsyncResult result = func.BeginInvoke(obj1, Completed, func); // do other stuff . . . private void Completed(IAsyncResult result) { ((FuncDelegate)result.AsyncState).EndInvoke(result); // do other cleanup }
更现代的方法是使用.NET 4 TPL中的任务 。