简体   繁体   English

需要有关线程安全的建议

[英]Need advice on thread safety

Is it safe to write code in this way? 以这种方式编写代码是否安全?

        var form = new Form();

        Action callback = 
            () =>
                {
                    // do something 1
                };

        ThreadPool.QueueUserWorkItem(
            args =>
                {
                    // do something 2
                    form.BeginInvoke(callback);
                });

UPD I'm concerned about safety of access to the "form" variable. UPD我担心访问“表单”变量的安全性。 I use BeginInvoke method from background thread; 我从后台线程使用BeginInvoke方法; can I be sure there won't be any read/write reordering before this moment? 我能确定在此之前不会有任何读/写重新排序吗? (that potentially can leave "form" variable in inconsistent state, from perspective of the background thread) (从后台线程的角度来看,可能会使“form”变量处于不一致状态)

Yes, it looks OK. 是的,它看起来不错。 The variable form will be captured and as long as it's not null when the job on the ThreadPool executes it ought to work. 将捕获变量form ,只要在ThreadPool上的作业执行时它不为null ,它应该工作。

But you left out a lot of details, I assume this code is all from 1 method. 但是你遗漏了很多细节,我假设这个代码全部来自1种方法。

// do something 1 can acess the GUI, // do something 2 can not. // do something 1可以访问GUI, // do something 2不能。

ThreadPool.QueueUserWorkItem(
args =>
{
    // do something 2
    form.BeginInvoke(x);
});

What actually happens here is the compiler creates a brand new class for you, and inside it there's a member variable that holds your Form instance. 这里实际发生的是编译器为您创建一个全新的类,并在其中有一个成员变量来保存您的Form实例。 This class is new'd up and then passed to the ThreadPool.QueueUserWorkItem() . 这个类是新的,然后传递给ThreadPool.QueueUserWorkItem() So yes, it's thread safe. 所以是的,这是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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