需要有关线程安全的建议
以这种方式编写代码安全吗?
var form = new Form();
Action callback =
() =>
{
// do something 1
};
ThreadPool.QueueUserWorkItem(
args =>
{
// do something 2
form.BeginInvoke(callback);
});
UPD 我担心访问“form”变量的安全性。我从后台线程使用 BeginInvoke 方法;我可以确定在此之前不会有任何读/写重新排序吗? (从后台线程的角度来看,这可能会使“form”变量处于不一致的状态)
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 thread)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,看起来不错。变量
form
将被捕获,只要在 ThreadPool 上的作业执行时它不为null
,它就应该可以工作。但你遗漏了很多细节,我假设这段代码全部来自 1 个方法。
// do Something 1
可以访问 GUI,// do Something 2
不能。Yes, it looks OK. The variable
form
will be captured and as long as it's notnull
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.这里实际发生的是编译器为您创建一个全新的类,其中有一个成员变量保存您的
Form
实例。这个类是新建的,然后传递给ThreadPool.QueueUserWorkItem()
。所以是的,它是线程安全的。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 theThreadPool.QueueUserWorkItem()
. So yes, it's thread safe.