Posts Tagged ‘cross thread’

Safe Cross Thread UI Access

Wednesday, May 21st, 2008

When you have multiple threads running in your application and have a user interface you’ll eventually run into the fact that UI elements are only allowed to be called from the same thread they are created in. The fast workaround for this is to set the CheckForIllegalCrossThreadCalls property of your controls to false but since we’re all good developers we want to solve this in a clean way.

There is an interface to track this behaviour called ISynchronizedInvoke which defines all the methods you need, this interface is implemented by the UI controls. You need to see if the property InvokeRequired is true and call Invoke (or BeginInvoke) to make your call thread safe. I used to declare a delegate for each different method signature I encountered since the Invoke methods take a delegate as argument. But there is a much more elegant way by using the MethodInvoker delegate and an anonymous delegate as you can see below. This prevents you from declaring a lot of delegates just for making your calls thread safe. This is illustrated below by a method in a presenter which updates my view.

public void IncomingMessage(ChatMessage msg)
{
    if (m_ChatView != null && m_ChatView.InvokeRequired)
    {
        m_ChatView.BeginInvoke(new MethodInvoker(delegate
        {
            IncomingMessage(msg);
        }), new object[] { msg }); return;
    }
    m_ChatView.DisplayMessage(BuildIncomingDisplayMessage(msg));
}