繁体   English   中英

从工作线程但不是主线程访问时,C# - 类字段为null

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM