AdSense

Monday, 2 September 2013

C# WPF - Invoke

(Deutsche Version) In the previous post there was this problem: I am only allowed to access graphics from the main thread. Unfortunately it can occur that you want to edit something from another thread. The solution for this problem is: invoke. At first a small example which does not work:

void threadActivity()
{
    Thread.Sleep(5000);
    TaskbarItemInfo.ProgressValue = 0.2;
}


After 5 seconds, there will be an error: InvalidOperationException has not been handled. The calling thread cannot acces this object, because the object belongs to another thread. As announced, the solution is called invoke. The new code looks like this:

void threadActivity()
{
    Thread.Sleep(5000);
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
        TaskbarItemInfo.ProgressValue = 0.2;
    }));
}


After 5 seconds, the progress bar in the task bar will be set to the value 0.2. About the syntax: Everything inside the curly braces is executed in the main thread. Inside the curly braces you can access variables which are also accessible from outside the curly braces. You can also have lots of code in here, but I would recommend to only invoke small code blocks.

No comments:

Post a Comment