在使用async和await时遇到问题? [英] Problem in working with async and await ?
本文介绍了在使用async和await时遇到问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我正在尝试将文件上传到Azure Blob存储,并在成功上传后将文件名添加到列表中以进行进一步的操作.当我执行同步时,它工作正常,但是当我执行异步时,发生了错误.
错误:集合已被修改;枚举操作可能无法执行.
foreach ( var 文件在文件中)
{
// .....
等待 blockBlob.UploadFromStreamAsync(fs);
listOfMovedLabelFiles.Add(fileName);
}
如果(listOfMovedLabelFiles.Count > // // 我的代码可供进一步操作
}
有什么方法可以等待所有异步操作完成.
解决方案
如果它是控制台应用程序,则必须使用 Async 如下.
注意:这只是一个示例.请根据您的应用进行调整.
class Program { static int Main(string[] args) { try { return AsyncContext.Run(() => MainAsync(args)); } catch (Exception ex) { Console.Error.WriteLine(ex); return -1; } } static async Task<int> MainAsync(string[] args) { ... } }
阅读更多信息:异步控制台程序
Hi
I am trying to upload files to Azure Blob Storage and after successful upload adding the filename to a list for my further operation. When i am doing synchronous it works fine but when i am doing async the error occured.
Error : Collection was modified; enumeration operation may not execute.
foreach(var file in files)
{
// .....
await blockBlob.UploadFromStreamAsync(fs);
listOfMovedLabelFiles.Add(fileName);
}
if (listOfMovedLabelFiles.Count > 0) // error point
{
// my code for further operation
}
Is there any way to wait till all the async operations get completed.
解决方案
If it''s a console app then you have to use Async is as below.
Note: This is just a sample.Adjust it according to your app.
class Program { static int Main(string[] args) { try { return AsyncContext.Run(() => MainAsync(args)); } catch (Exception ex) { Console.Error.WriteLine(ex); return -1; } } static async Task<int> MainAsync(string[] args) { ... } }
Read for more info : Async Console Programs
这篇关于在使用async和await时遇到问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文