First off, you may or may not be able to post a message to the thread which called Start
: you'll only be able to do this if the thread has a message queue associated with it, and is checking that queue. UI threads do this, but e.g. threadpool threads, or threads which you've created with new Thread()
, won't.
If a thread has a message queue associated with it, it's common practice to install a SynchronizationContext
on that thread. You can fetch a thread's SynchronizationContext
using SynchronizationContext.Current
, store it away, and then post messages to that thread's message queue using that SynchronizationContext
. If a thread doesn't have a SynchronizationContext
installed on it, SynchronizationContext.Current
returns null
.
public event EventHandler StatusChanged;
private Timer timer;
private SynchronizationContext synchronizationContext;
public void Start()
{
synchronizationContext = SynchronizationContext.Current;
StatusChanged += new EventHandler(SomethingChangedMethod);
timer = new Timer(Pending, null, 0, 1000);
}
private void Pending(object state)
{
// Do Something
if (synchronizationContext != null)
{
synchronizationContext.Post(_ => StatusChanged?.Invoke(this, EventArgs.Empty), null);
}
else
{
StatusChanged?.Invoke(this, EventArgs.Empty);
}
}