CodeSnippet: Multithreading your app

1 April 2008 Tags  , , ,

Ever noticed how some applications tend to hang when you perform an operation? For example in MahTweets (my Twitter client), it used to have a looong pause every time it updated the Tweet list, and often the application would go black, almost to the 'not responding' stage. The GUI and application logic shared the same thread, meaning a massive change in GUI or lots of processing in the logic would stop the other.

The way around this is to use a separate thread for anything that requires a lot of processing, or that is bottled by another factor (Disk IO, or network speed, etc).

public delegate void MyDelegate();

// This method could be the method behind a button.clickpublic void InvokingMethod()
{
    Thread myThread = new Thread(new ThreadStart(new MyDelegate(MyMethod)));
    myThread.Start();
}
public void MyMethod()
{
    //Code to execute on new thread goes here
}

There is one caveat, your new thread cannot access the GUI because this could cause some serious synchronisation issues. The way around this (in WPF at least!) is to use the Dispatcher.Invoke method.

public void GuiMethod()
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(DispatcherPriority.Normal, new voidDelegate(GuiMethod));
        return;
    }

    //Code that accesses the GUI
}

If you need to pass parameters, one (quick) way is with an anonymous delegate like below, I'll let you figure out the different ways to go about it though.

Thread t = new Thread(delegate() { MyMethod(MyParam); });

If you are having problems with concurrency and synchronisation, that's outside the scope of this post…start looking at wikipedia's article on threading, and go from there.


Comments

Trackbacks / Pingbacks

Comments are closed