C# 获取线程类与主类通信

标签 c# .net

我有一些 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/

相关文章:

c# - 如何制作具有用于管理它的任务托盘图标的 Windows 服务?

c# - 无法使用 C# (NewtonSoft) 编辑 JSON,因为出现错误

c# - 该属性必须是有效的实体类型,并且该属性应该具有非抽象 getter 和 setter。 Entity Framework

c# - 如果用户定义函数的静态调用顺序违反了一些规则,让编译器提示

c# - 将 C# 翻译成 VB

c# - Windows 事件查看器中未显示新的 Windows 日志

c# - 在教新开发人员时,我应该从单元测试开始吗?

c# - 为什么 LET 语句的顺序在此 Entity Framework 查询中很重要?

c# - 在 Python 中压缩并使用解压缩 C# 解压缩的最简单方法(反之亦然)

.net - 如何使 IEnumerable<string>.Contains 不区分大小写?