4

I have some code that executes and gets the return value of execution. I set this value to a dependency property of my window because there are style triggers bound to it. When the variable is 0 it uses the default style, when 1 a reddish style, and when 2 a greenish.

But i have to reset this style after a while in some practical way.

What is the easiest method to do this?

if (!Compiler.TryCompile(strText, Models[Model], EntryPoint.Text, out error))
{
    output.Items.Add("Error compiling:");
    output.Items.Add(error);
    CompilationStatus = 1; // dependency property bound on ui
}
else {
    output.Items.Add("Compilation successful!");
    CompilationStatus = 2; // dependency property bound on ui
}

// should execute this after 5 seconds 
CompilationStatus = 0;  // dependency property bound on ui

WPF and .Net 4 is used in project. Thanks!!

Sandi Uran
  • 41
  • 2

2 Answers2

2

I usually use a custom extension method for this:

public static class DispatcherHelper
{
    public static void DelayInvoke(this Dispatcher dispatcher, TimeSpan ts, Action action)
    {
        DispatcherTimer delayTimer = new DispatcherTimer(DispatcherPriority.Send, dispatcher);
        delayTimer.Interval = ts;
        delayTimer.Tick += (s, e) =>
        {
            delayTimer.Stop();
            action();
        };
        delayTimer.Start();
    }
}

In your case you can then use it like this:

Dispatcher.DelayInvoke(TimeSpan.FromSeconds(5), () => 
{
   CompilationStatus = 0; 
}

Edit: I had forgotten, but looks like this method originally was written by Jon Skeet in this SO thread: Delayed Dispatch Invoke?

Community
  • 1
  • 1
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
0

If time exactness is not an issue, and since you are using WPF and .Net 4 this is a very easy one, just replace you code with the following:

new Task(delegate() {
  Thread.Sleep(5000);
  Dispatcher.Invoke((Action)delegate(){
     CompilationStatus = 0;
  });
}).Start();

It will invoke on the UI thread through the dispatcher, so you should be safe.

This Fire@Forget method is not very exact and could lag if the CPU is under stress. If that is a no-go for you then you should use the Stopwatch class in System.Diagnostics.

Marino Šimić
  • 7,318
  • 1
  • 31
  • 61