在C#中的Parallel.Foreach循环中将Tuple添加为线程安全输入

时间:2017-09-05 13:03:19

标签: c# multithreading parallel-processing

我需要C#中Parallel.Foreach循环的帮助。我有一种感觉,有时"结果"元组由其他并行线程重写,因此没有正确的输出。它并不经常发生,但有时会吐出不好的结果。

场景:网络设备是可访问的,一切正常,输出存储在"结果"元组。但是当我使用"结果"此外,即使输出存储在那里,元组有时也是空的。可能是并行处理中的其他线程正在擦除"结果" ?我可以让它更安全吗?

Tuple <string, int> result;

/*loop through all hosts and execute commands -> In paralel*/
        Parallel.ForEach(devices, (hostname, state) =>
        {
            //because we have multithreading every thread must differentiate -> based on hostname (first value in list) - key is also hostname
            device_checked_with_all_parameters.Add(cleaned_hostname, new List<string> { DateTime.Now.ToString("d.M.yyyy HH:mm:ss"), cleaned_hostname, "", "", "", "" });

                //if stop is pushed break all threads
            if (token.IsCancellationRequested)
            {
                canceled_loop = 1;
                state.Break();
            }

            //PERFORM ACTION ON DEVICE - STORE OUTPUT IN RESULT
            result = core.connect_to_device_and_perform_actions(device_checked_with_all_parameters[cleaned_hostname][1], config_vlan_ids_based_on_type);

         });

0 个答案:

没有答案