我有一些 C# 线程必须根据数字执行一些工作,但是我不确定如何让线程对象与主程序类进行通信。我需要它告诉主对象它已经找到结果以及结果是什么,然后它可以停止线程。
Worker Worker1 = new Worker(input, 1073741824, 2147483647);
Worker Worker2 = new Worker(input, 0, 1073741824);
Thread ThreadRace1 = new Thread(new ThreadStart(Worker1.Start));
Thread ThreadRace2 = new Thread(new ThreadStart(Worker2.Start));
ThreadRace1.Start();
ThreadRace2.Start();
最佳答案
如果您使用的是 .NET 4.0+,则可以使用 TPL 。代码看起来像这样:
var task1 = Task.Factory.StartNew<int>(()=>
{
//Do Work...use closures, or you can pass boxed arguments in
//via StartNew params
return 1;//return the value that was computed
});
var task2 = Task.Factory.StartNew<int>(()=>
{
//Do Work
return 2;//return the value that was computed
});
task1.ContinueWith((previousTask)=>
{
//Return back to the main thread
label1.Text += "The value of task1 is going to be 1-->"
+ previousTask.Result;
}
, new CancellationTokenSource().Token, TaskContinuationOptions.None,
//This is to auto invoke back into the original thread
TaskScheduler.FromCurrentSynchronizationContext());
task2.ContinueWith((previousTask)=>
{
//Return back to the main thread
label1.Text += "The value of task2 is going to be 2-->"
+ previousTask.Result;
}
, new CancellationTokenSource().Token, TaskContinuationOptions.None,
//This is to auto invoke back into the original thread
TaskScheduler.FromCurrentSynchronizationContext());
如果您不需要在他们进来时处理每个人,那么您可以等待他们全部返回:
var taskList = new List<Task>{task1,task2};
Task.Factory.ContinueWhenAll(taskList.ToArray(),
(tasks)=>
{
label1.Text = "Results are: ";
foreach(var task in tasks)
{
//process each task
label1.Text += task.Result + "|";
}
},
new CancellationTokenSource().Token, TaskContinuationOptions.None,
//This is to auto invoke back into the original thread
TaskScheduler.FromCurrentSynchronizationContext());
关于C# 获取线程类与主类通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489854/