我在一个小的C# WPF应用程序中使用异步和等待,这样我就可以在后台运行长时间的处理操作时阻止gui被阻塞。我的应用程序的上下文是从CSV读取数据并将其转换为XML文档。
当我使用1999个条目的输入列表计数运行以下代码时,最终得到的迭代计数约为8000。
**** Main Thread ****
outputItems = await CreateOutputItems(inputItems);
**** End Main Thread ****
public async Task<IEnumerable<ConvertedEntity>> CreateOutputItems(IEnumerable<InputEntity> inputItems)
{
return await Task.Run(() => inputItems.Select(CreateOutputItemFromInputItem));
}
当我删除它并在主线程中将其作为过程循环运行时,我得到了正确的1999次迭代。
var convertedItems = new List<ConvertedEntity>();
foreach (var inputItem in inputItems)
{
var outputItem = CreateOutputItemFromInputItem(inputItem);
convertedItems.Add(outputItem);
}
另外,我注意到我的ConvertedEntity中包含ID号(仅仅是循环/迭代号)的字段在使用async await时被损坏。例如,值是2000,4000,6000到30,000,当我使用foreach循环时,它们是1,2,3,4,5等等。
有什么想法吗?
发布于 2017-02-14 05:14:35
将int
输入参数添加到您的方法中,这样您就可以使用带有索引的Select
版本,然后使用该索引i
来正确设置ID
public ConvertedEntity CreateOutputItemFromInputItem(InputEntity x, int i)
{
// now use i to set the ID
还要在Select(CreateOutputItemFromInputItem)
后面添加一个.ToList()
,这样它就可以在Task.Run
中执行它
https://stackoverflow.com/questions/42216574
复制相似问题