且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在使用async和await时遇到问题?

更新时间:2022-10-18 07:39:29

如果它是控制台应用程序,则必须使用 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