C# - 从工作线程而不是主线程访问时,类字段为空
不确定我做错了什么:
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
}
}
Not sure what I'm doing wrong:
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为我们需要看到可重现的代码,但我可以看到 4 种情况:
MyClass
实例对话 - 我的赌注在这里eventInfo
的变量(如果有任何歧义,请尝试使用this.eventInfo
当您指的是该字段)易失性
;再次不太可能)前两个更有可能。
I think we'd need to see reproducible code, but I can see 4 scenarios:
MyClass
instance in the two cases - my bet is hereeventInfo
in one of the methods (try usingthis.eventInfo
when you mean the field if there is any ambiguity)volatile
; again unlikely)The first two are much more likely.
您需要至少执行以下操作之一:
使
eventInfo
易失性,以确保OnGenerateEvent()
在调用 < code>someMethodInfo.Invoke()使用互斥锁/锁之类的东西来保护对
eventInfo
的访问。这还将提供适当的内存屏障(我认为这才是真正应该做的)哦,我假设实际上没有涉及 2 个不同的
MyClass
实例 - 那不能通过您所显示的代码进行验证。You'll need to do at least one of the following:
make
eventInfo
volatile to ensure thatOnGenerateEvent()
writes it all the way out to memory before callingsomeMethodInfo.Invoke()
use something like a mutex/lock to protect access to
eventInfo
. This will also provide the proper memory barriers (this is what really should be done in my opinion)Oh, and I'm assuming that there aren't really 2 different
MyClass
instances involved - that can't be verified by the code you've shown.