我想通过一个函数,它的一个参数的ThreadStart构造函数,C#。但是,看来这是不可能的,因为我得到一个语法错误是我尝试做这样的事情传递参数给线程
Thread t1 = new Thread(new ThreadStart(func1(obj1));
其中OBJ1是List<string>
类型的对象(说)。
如果我想要一个线程来执行此功能,在一个对象作为参数,我打算同时创建2级这样的线程具有不同的参数值是什么,是实现这一目标的最佳方法是什么?
我想通过一个函数,它的一个参数的ThreadStart构造函数,C#。但是,看来这是不可能的,因为我得到一个语法错误是我尝试做这样的事情传递参数给线程
Thread t1 = new Thread(new ThreadStart(func1(obj1));
其中OBJ1是List<string>
类型的对象(说)。
如果我想要一个线程来执行此功能,在一个对象作为参数,我打算同时创建2级这样的线程具有不同的参数值是什么,是实现这一目标的最佳方法是什么?
你需要ParametrizedThreadStart
一个参数传递给线程。
Thread t1 = new Thread(new ParametrizedThreadStart(func1);
t1.Start(obj1);
如果您使用.NET 3.5或更高版本,一个选择是使用这个拉姆达:
var myThread = new System.Threading.Thread(() => func1(obj1));
非常感谢! – assassin 2010-05-12 05:07:38
试试这个:
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();
你可以像这样开始一个新的线程:
Thread thread = new Thread(delegate() {
// Code here.
});
thread.Start();
里面的anonymous method您有权访问是在范围上创建委托时的变量。
编辑刺客有麻烦此代码工作,所以我已经包括在这篇文章的最后一个完整的示例控制台应用程序。
{ // some code
Thread t1 = new Thread(MyThreadStart);
t1.Start(theList);
}
void MyThreadStart(object state)
{
List<string> theList = (List<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 Main(string[] args)
{
var list = new List<string>(){
"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<string>)
{
Console.WriteLine(item);
}
}
static void func1(object parameter)
{
// Do stuff here.
}
static void Main(string[] args)
{
List<string> obj1 = new List<string>();
Thread t1 = new Thread(func1);
t1.Start(obj1);
}
它使用.NET 2.0中新的代表呼吁ParameterizedThreadStart。你可以阅读关于它here。
你绝对需要使用Thread
对象?或者你只是在寻找多线程处理发生?更“现代”的方法是使用异步委托作为这样:
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使用Tasks。
您正在使用什么版本的.NET的? – 2010-05-11 16:57:34
哇!我之前通过创建一个包含该线程将使用的数据的类来实现此目的,但我不知道有这么多种不同的方法来对此动物进行蒙皮! – 2010-05-11 17:01:45