execute in ui thread

R

RedLars

Hi,

How can I make sure that the m_eventHandler code is executed in the
context of the UI thread given that the NotifySubscriber can be called
from a worker thread? This code is ran in .NET 3.5. Notice that the
class does not derive from either Form or Windows class.

internal class MyClass
{
private Action<string, int> m_eventHandler;
private string m_text;
private int m_int;

internal MyClass(Action<string, int> eventHandler)
{
m_eventHandler = eventHandler;
}

private void NotifySubscriber()
{
if (m_eventHandler != null)
{
m_eventHandler(m_text, m_int);
}
}
}
 
I

Ingunn Espelid

In general, classes not tied to a GUI framework such as Forms or WPF
should not include logic to worry about what thread code executes on.
That's for the subscriber to the event to worry about.

This ensures that the overhead of dealing with thread management exists
only when needed and only in the code where it's needed.

If your class _is_ specifically for supporting thread-tied GUI
frameworks such as Forms or WPF, you can use the same approach that the
BackgroundWorker class does: store the current SynchronizationContext
object when your class instance is initialized, and then use the Send()
and/or Post() methods on that SynchronizationContext to execute event
handlers.

Pete

Thanks for the response Pete.

Will give your suggestion a try tomorrow.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top