public class WmSync : IDisposable
{
public WmSync()
{
var sync = new Control();
sync.Handle.GetHashCode(); // ensure handle is created
_sync = sync;
Thread.MemoryBarrier();
}
public void Dispose()
{
_sync.Dispose();
}
public void BeginInvoke(Action action)
{
_sync.BeginInvoke(action);
}
public void Invoke(Action action)
{
_sync.Invoke(action);
}
public bool InvokeRequired
{
get { return _sync.InvokeRequired; }
}
private readonly Control _sync;
}
The idea is to create this object in the main thread and use it from background threads to execute pieces of code in the main thread.
For example:
// somewhere in the very beginning of the program, in the main thread
static WmSync SyncQueue = new WmSync();
// somewhere in a background thread
SyncQueue.Invoke(
() =>
{
if (_settingsForm != null)
_settingsForm.Show();
});
This is just an artificial sample, but it should give you idea. Is this code thread safe?
1 Answer 1
Thread.MemoryBarrier()
What do you expect the call to Thread.MemoryBarrier()
will help your code ?
What does Thread.MemoryBarrier
do ? It prevents that the compiler and the hardware subtly transform a program’s memory operations.
So basically for your code it ensures that then following instructions will be executed in the order they are written.
var sync = new Control(); sync.Handle.GetHashCode(); // ensure handle is created _sync = sync;
Thread safety
To answer "Is this code thread safe ?", you first need to set your definition of thread safety aka what does thread safety means for you. See also what-is-this-thing-you-call-thread-safe
General
the code is lacking a
EndInvoke()
which should be integrated.you are misusing a
Control
to access the main (ui) thread of an application.wouldn't a
SynchronizationContext
be a better fit here ?
-
\$\begingroup\$ in the first place, this class was never supposed to be used in UI. The idea is to pass execution to the main thread, it's the one and only function of this class. \$\endgroup\$user626528– user6265282015年01月02日 08:58:01 +00:00Commented Jan 2, 2015 at 8:58
-
\$\begingroup\$ "2. you are misusing a Control" - in the same way everyone (including MS) does. "3. wouldn't a SynchronizationContext be a better fit here" - how exactly? \$\endgroup\$user626528– user6265282015年01月07日 03:37:44 +00:00Commented Jan 7, 2015 at 3:37
-
\$\begingroup\$ @user626528 if it's not a UI application, then what is the definition of "main thread" then? Why can't you run your logic in the "background" threads? Please describe why you need to capture a certain thread and name it "main" \$\endgroup\$almaz– almaz2015年02月04日 16:23:54 +00:00Commented Feb 4, 2015 at 16:23
Explore related questions
See similar questions with these tags.
The idea is to create this object in the main thread and use it from background threads to execute pieces of code in the main thread
by updating your question. Some real world example would help also. \$\endgroup\$