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)
Yes, it looks OK. The variable
formwill be captured and as long as it’s notnullwhen 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 1can acess the GUI,// do something 2can not.