我怎样才能在c#中这样做?我有GUI和工作线程,我必须传递数组或能够从工作数组访问数组?!
Thread t = new Thread (delegate() { DoWork (double[,] data); });
t.Start();
static void DoWork (double[,] data) { do some work...; }
答案 0 :(得分:2)
使用参数化线程委托(ParameterisedThreadStart):
Thread t = new Thread(o =>
{
double[,] data = (double[,])o;
DoWork(data);
});
t.Start(myData);
编辑:或正如Paul在评论中建议的那样,通过闭包抓取myData:
Thread t = new Thread(() => DoWork(myData));
t.Start();
答案 1 :(得分:1)
所有线程委托都接受一个对象。传递数组,然后在工人中投射:
double[,] myarray = ...;
ThreadPool.QueueUserWorkItem(state=>{
double[,] arrayArg = (double[,])state;
DoWork(arrayArg);
}, myarray);
ThreadStart有类似的论点。确保在工作线控制下的UI线程中不触摸数组...
答案 2 :(得分:1)
来自MSDN:
class Test
{
static void Main()
{
Work threadWork = new Work(yourdata);
Thread newThread =
new Thread(new ThreadStart(threadWork.DoWork));
newThread.Start();
}
}
class Work
{
private double[,] myData;
public Work(double[,] data) {
myData = data;
}
public void DoWork() { /* use myData */ }
}