我试图找出azure worker角色如何启动RoleEnvironment事件以及它如何影响字段访问。
参考我下面的代码示例,我的理解是:
这是否意味着RoleEnvironmentChanged和OnStop将无法引用实例字段_someClass,我是否必须将其设置为静态?或者事件处理程序是否在实例变量周围有一个闭包?
这是一个简化的例子:
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.
}
}
答案 0 :(得分:1)
您的2个语句是正确的(事件处理程序在与Run()方法不同的线程上运行),但这与访问WorkerRole类的成员变量没有任何关系。事件处理程序中的代码是实例方法,而不是静态方法,因此它们可以访问类的成员。