小编Der*_*ton的帖子

如果从不读取值,让多个线程写入同一个 bool 是否安全?

我想出了一个有趣的情况。我有一个 bool 变量,然后我希望多个线程执行自己的独立任务,然后根据线程的结果标记该 bool。此变量永远不会被任何线程读取,并且在所有写入测试完成之前永远不会使用。像这样:

public bool F(){
    bool flag = false;
    Parallel.ForEach(list, element => 
    {
        bool result = // Do independent work here;
        if (result) flag = true;
    });
    return flag;
}
Run Code Online (Sandbox Code Playgroud)

Notice how I never read flag inside my Parallel.ForEach. But what could happen is having multiple threads attempting to write true to flag (but never false). Is it safe to do this?

c# concurrency multithreading thread-safety

4
推荐指数
1
解决办法
647
查看次数

应该等待Parallel.Foreach吗?

这里发生了一件奇怪的事情.我以为Parallel.Foreach会等到所有任务完成后再继续.但是,我有类似的东西:

List<string> foo(List<A> list){
    Dictionary<string, bool> dictionary = new Dictionary<string, bool>();
    Parallel.Foreach(list, element =>
    {
        dictionary[element.Id] = true;
        if (element.SomeMethod()){
            dictionary[element.Id] = false;
        }
    });

    List<string> selectedIds = (from element in list where !dictionary[element.Id] select element.Id).ToList();
    return selectedIds;
}
Run Code Online (Sandbox Code Playgroud)

然后我在选择行中得到System.Collections.Generic.KeyNotFoundException(有时,并不总是).正如您所看到的,我正在为每个可能的键(列表元素的ID)初始化字典,然后获得此异常,这使我认为在执行Parallel.Foreach完成之前可能会到达此行...是对的吗?如果是这样,我怎么能等到这个Parallel.Foreach的所有分支完成?

c# asynchronous task-parallel-library

1
推荐指数
1
解决办法
2161
查看次数