开发者

Need advice on thread safety

开发者 https://www.devze.com 2023-04-12 22:01 出处:网络
Is it safe to write code in this way? var form = new Form(); Action callback = () => { // do something 1

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. I use BeginInvoke method from background thread; 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 th开发者_如何学运维read)


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.

But you left out a lot of details, I assume this code is all from 1 method.

// do something 1 can acess the GUI, // do something 2 can not.


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. This class is new'd up and then passed to the ThreadPool.QueueUserWorkItem(). So yes, it's thread safe.

0

精彩评论

暂无评论...
验证码 换一张
取 消