并行任务之间的同步值 [英] synchronization values between tasks parallel foreach

查看:47
本文介绍了并行任务之间的同步值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i有一个foreach循环,它占用了当前更多的时间,我想改为Parallel.ForEach,所以有没有办法分享变量的值,如< b> finalResult< / b个和< b> testResult< / b>在并行任务中,即每个任务从共享位置获取值并更新它,以便下一个任务可以选择更新的值等等。

有人可以帮助我如何实现这个目标吗? br />

Hi ,
i have one foreach loop which is taking currently more time and i am thinking to change to Parallel.ForEach, so is there any way to share the values of variables like <b>finalResult</b> and <b>testResult</b> among the parallel task, i.e each task get the value from shared location and update it,so that next task can pick the updated value an so on.
Could someone please help me how to achieve this?

protected Data mytest(ref Check testResult, CancellationToken token, bool logOnError, bool logOnSuccess)
{
           Data finalResult = new Data(ActionStatus.Success);
            foreach (Check data in mydata.Values)
            {

                Data result = watcher.ExecuteOnce();
                Logger.Write(LogType.Info,result.Status == Success ? "succeeded" : "failed");
                finalResult = GetHighestPriority(finalResult, result, ref testResult, data);


            }
            return finalResult;
}





谢谢..



Thanks..

推荐答案

Hi


使用volatile关键字



Hi
Use volatile keyword

public volatile int i;

       public void Test(int _i)
       {
           i = _i;
       }


这篇关于并行任务之间的同步值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆