异步/等待处于天蓝色工作角色的角色,导致角色回收 [英] Async/await in azure worker role causing the role to recycle
问题描述
我正在我的WorkerRole(RoleEntryPoint)中处理Tasks,Async和await.
I am playing around with Tasks, Async and await in my WorkerRole (RoleEntryPoint).
我进行了一些无法解释的回收,现在我发现,如果等待调用中的某些东西运行很长时间,则该角色将回收.要重现它,只需在Run方法中等待a Task.Delay(60000).
I had some unexplained recycles and i have found out now that if something is running to long in a await call, the role recycles. To reproduce it, just do a await Task.Delay(60000) in the Run method.
任何可以向我解释原因的人吗?
Anyone who can explain to me why?
推荐答案
Run
方法必须块.来自文档:
如果您确实重写Run方法,则您的代码应无限期地阻塞.如果Run方法返回,则通过引发Stopping事件并调用OnStop方法来自动回收角色,以便可以在使角色脱机之前执行关闭序列.
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);
}
}
或者,您可以在我的AsyncEx库中使用 AsyncContext
Alternatively, you can use AsyncContext
from my AsyncEx library:
public override void Run()
{
AsyncContext.Run(async () =>
{
while (true)
{
await Task.Delay(60000);
}
});
}
无论选择哪个选项,Run
都应不是为async
.类似于控制台应用程序的Main
(请参阅我的博客以了解原因async Main
不允许).
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).
这篇关于异步/等待处于天蓝色工作角色的角色,导致角色回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!