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?
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\$