【发布时间】:2015-04-29 01:49:19
【问题描述】:
给定一些这样的代码
public class CustomCollectionClass : Collection<CustomData> {}
public class CustomData
{
string name;
bool finished;
string result;
}
public async Task DoWorkInParallel(CustomCollectionClass collection)
{
// collection can be retrieved from a DB, may not exist.
if (collection == null)
{
collection = new CustomCollectionClass();
foreach (var data in myData)
{
collection.Add(new CustomData()
{
name = data.Name;
});
}
}
// This part doesn't feel safe. Not sure what to do here.
var processTasks = myData.Select(o =>
this.DoWorkOnItemInCollection(collection.Single(d => d.name = o.Name))).ToArray();
await Task.WhenAll(processTasks);
await SaveModifedCollection(collection);
}
public async Task DoWorkOnItemInCollection(CustomData data)
{
await DoABunchOfWorkElsewhere();
// This doesn't feel safe either. Lock here?
data.finished = true;
data.result = "Parallel";
}
正如我在几个 cmets inline 中指出的那样,执行上述操作对我来说并不安全,但我不确定。我确实有一个元素集合,我想为每个并行任务分配一个唯一元素,并让这些任务能够根据完成的工作修改集合的单个元素。最终结果是,我想在并行修改不同元素之后保存集合。如果这不是一种安全的方法,我该怎么做?
【问题讨论】:
-
我假设
DoWorkOnItemInCollection里面至少有一个await你没有显示,对吗? -
是的,这很简单。我会添加一些东西来等待。
-
你的代码不会编译,你不能像
DoWorkInParallel那样在非async方法中使用await。 -
这是一个错字,它是异步的。固定。
-
我假设
DoWorkInParallel是由单个线程调用的,对吧?
标签: c# .net multithreading task-parallel-library