0
我想弄清楚azure工作者角色如何啓動RoleEnvironment事件以及這會如何影響字段訪問。您可以從RoleEnvironment.OnRoleChanging事件處理程序中訪問實例字段嗎?
參考我下面的代碼示例,我的理解是:
- 的RoleEnvironmentChanging和RoleEnvironmentChanged事件處理程序將在啓動事件的線程的上下文中運行
- 事件線程會不同於被AutoResetEvent阻擋的線程
這是否意味着RoleEnvironmentChanged和OnStop將無法引用實例字段_someClass,我是否必須將它設置爲stati C?或者事件處理程序在實例變量周圍有一個閉包?
下面是一個簡單的例子:
public abstract class WorkerRole : RoleEntryPoint
{
private readonly AutoResetEvent _eventHandler = new AutoResetEvent(false);
private SomeClass _someClass;
public override bool OnStart()
{
RoleEnvironment.Changing += RoleEnvironmentChanging;
RoleEnvironment.Changed += RoleEnvironmentChanged;
_someClass = new SomeClass();
return base.OnStart();
}
public override void OnStop()
{
// Tell the other class to stop
_someClass.Stop();
base.OnStop();
}
public override void Run()
{
// Start some process in another class that executes on a different thread internally.
_someClass.Run()
_eventHandler.WaitOne(); // Wait, so the method doesn't return and the role restart.
base.Run();
}
private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
{
e.Cancel = false // Never restart the role (just for this example)
}
void RoleEnvironmentChanged(object sender, RoleEnvironmentChangedEventArgs e)
{
_SomeClass.Refresh() // Just proving I can call this variable from here.
}
}