【发布时间】:2021-03-08 20:38:45
【问题描述】:
我遇到了一些问题,projectLogDict 没有更新 ImageCount。如果你看下面的代码,我有var drawingCount 和var imageCount,我将它们添加到Task.WhenAll。
问题在于imageCount 的值似乎从未在projectLogDict 中更新。但是,如果我注释掉 var drawingCount,imageCount 的值会起作用并在 projectLogDict 中更新
我不确定为什么不能在projectLogDict 中更新这两个值。
有没有办法同时更新drawingCount 和imageCount 并将其添加到projectLogDict 中?
public async Task<ConcurrentDictionary<string, ProjectLogs>> GetProjectFiles(ConcurrentDictionary<string, ProjectLogs> projectLogDict)
{
var locations = await _test.GetAllLocations().ConfigureAwait(false);
foreach(var branch in locations)
{
var projects = await _test.GetLocationProjectsAsync(branch).ConfigureAwait(false);
var task = new List<Task<ConcurrentDictionary<string, ProjectLogs>>>();
var taskTwo = new List<Task<ConcurrentDictionary<string, ProjectLogs>>>();
foreach (var project in projects)
{
var drawingCount = GetDrawingCount(project.Id);
var imageCount = GetImageCount(project.Id);
taskTwo.Add(imageCount);
task.Add(drawingCount);
}
var x = await Task.WhenAll(task.ToArray()).ConfigureAwait(false);
var y = await Task.WhenAll(taskTwo.ToArray()).ConfigureAwait(false);
}
return projectLogDict;
}
public async Task<ConcurrentDictionary<string, ProjectLogs>> GetImageCount(string projectId)
{
var files = await _test.GetUploadFilesAsync(projectId, null).ConfigureAwait(false);
projectLogDict.AddOrUpdate(projectId, new ProjectLogs { ImageCount = file.count() }, (key, value) => value = new ProjectLogs { ImageCount = file.count() });
return projectLogDict;
}
public async Task<ConcurrentDictionary<string, ProjectLogs>> GetDrawingCount(string projectId )
{
var drawingCount = await _test.GetItemsDrawing(projectId).ConfigureAwait(false);
projectLogDict.AddOrUpdate(projectId, new ProjectLogs { DrawingCount = drawingCount.Count() }, (key, value) => value = new ProjectLogs { DrawingCount = drawingCount.Count() });
return projectLogDict;
}
【问题讨论】:
-
您不需要 ConcurrentDictionary,因为您没有对字典进行并发写入。另外,我希望
GetDrawingCount和GetImageCount有一个projectLogDict参数。目前还不清楚他们甚至从哪里得到他们的 projectLogDict,以及它是否与GetProjectFiles收到的相同。这只是在等待一些令人讨厌的惊喜发生在您认为自己正在使用同一本词典的地方,但实际上并非如此。
标签: c# asp.net asynchronous task