I want to do something like the following – basically I am calling an async operation which will call a callback in another thread and I want to wait for it to complete “inline”. My worry is that that changes variables shared across threads (bar & event) may not be synchronized due to being stored in registers for example. If they were member variables I could mark them volatile but volatile can’t be used on local variables created on the stack. I could use member variables but I think its cleaner not clutter my class by keeping it all local.
Bar bar = null;
ManualResetEvent event = new ManualResetEvent(false);
foo.AsyncOperation(new Action(()=>{
// This delegate will be called in another thread
bar = ...
event.Set();
}));
event.WaitOne(timeout);
// use bar
Yes, it will work correctly. Read here
http://www.albahari.com/threading/part4.aspx
The following implicitly generate full fences:Setting and waiting on a signaling constructand in the signaling constructs the
ManualResetEventis included.If you want to know what a
full fenceis, in the same page: