Async/await in azure worker role causing the role to recycle

前端 未结 2 623
情话喂你
情话喂你 2021-02-13 17:08

I am playing around with Tasks, Async and await in my WorkerRole (RoleEntryPoint).

I had some unexplained recycles and i have found out now that if something is running

2条回答
  •  灰色年华
    2021-02-13 17:37

    The Run method must block. From the docs:

    If you do override the Run method, your code should block indefinitely. If the Run method returns, the role is automatically recycled by raising the Stopping event and calling the OnStop method so that your shutdown sequences may be executed before the role is taken offline.

    A simple solution is to just do this:

    public override void Run()
    {
      RunAsync().Wait();
    }
    
    public async Task RunAsync()
    {
      while (true)
      {
        await Task.Delay(60000);
      }
    }
    

    Alternatively, you can use AsyncContext from my AsyncEx library:

    public override void Run()
    {
      AsyncContext.Run(async () =>
      {
        while (true)
        {
          await Task.Delay(60000);
        }
      });
    }
    

    Whichever option you choose, Run should not be async. It's kind of like Main for a Console app (see my blog for why async Main is not allowed).

提交回复
热议问题