Dispatcher.CurrentDispatcher.BeginInvoke Not Invoking

MoonKnight picture MoonKnight · Nov 22, 2013 · Viewed 15.4k times · Source

I have a FileSystemWatcher and the events raised by this when a watched file changes are raised on a different thread from the UI thread. To avoid and cross-thread acess volation fun, I am attempting to use

public void RaisePathChanged(object sender, RenamedEventArgs e)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => 
    {
        // Some code to handle the file state change here.
    }));
}

This compiles fine and the RaisePathChanged is fired as it should be. However, the code inside the delegate Action(() => { /*Here*/ }) never gets called/invoked, the code is merely skipped.

Why is the code being skipped, how can I fix it and is this the best way to insure code is run on the thread that created it in WPF?

Thanks for your time.

Answer

dev hedgehog picture dev hedgehog · Nov 22, 2013

You are mixing up things.

Dispatcher.CurrentDispatcher is not the same as Application.Current.Dispatcher.

The second one is the one you seem to be looking for.

Take a look at this.

Dispatcher.CurrentDispatcher vs. Application.Current.Dispatcher

Try it out with application dispatcher.