[英]C# - class field is null when accessed from a worker thread but not main thread
不确定我做错了什么:
class MyClass
{
private EventInfo eventInfo;
public void OnGenerateEvent(object sender, EventArgs e)
{
// Called from *main* thread
// Load assembly and set eventInfo here
eventInfo = ....GetEvent(...);
eventInfo.AddEventHandler(source, handler);
// Call to a static method in another assembly
someMethodInfo.Invoke(null, null);
}
public void OnEventChanged(object sender, EventArgs args)
{
// Called from a *worker* thread created
// by that static method in the other assembly
eventInfo is null here !
// Trying to remove handler
eventInfo.RemoveEventHandler(.....);
}
// But...
protected override void Dispose(bool disposing)
{
// Called from *main* thread when program closes
eventInfo is *not* null here
}
}
我想我们需要看到可重现的代码,但我可以看到4个场景:
MyClass
实例交谈 - 我的赌注就在这里 eventInfo
的变量(如果你有任何歧义的话,请尝试使用this.eventInfo
) volatile
;再次不太可能) 前两个更有可能。
您至少需要执行以下操作之一:
使eventInfo
volatile以确保OnGenerateEvent()
在调用someMethodInfo.Invoke()
之前将其一直写入内存
使用类似互斥锁/锁的东西来保护对eventInfo
访问。 这也将提供适当的内存障碍(这是我认为应该做的)
哦,我假设没有真正涉及2个不同的MyClass
实例 - 无法通过您显示的代码进行验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.