Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interoperability between System.Windows.Forms.Application and System.Windows.Application

Tags:

c#

.net

interop

I have to integrate a WPF UI into a .NET 2.0 application.

ObservableCollection needs to be modified in the GUI Dispatcher thread, so I came up with a solution involving InvokeLater()

ObservableCollection<Item> items;
public delegate void AddItemDelegate(Item i);

public void AddItem(Item item)
{
    System.Windows.Application.Current.Dispatcher.BeginInvoke(
        new AddItemsDelegate(i => items.Add(i), item);
}

However, since the project was originally written with .NET 2.0, the main thread uses a System.Windows.Forms.Application, so System.Windows.Application.Current is null.

I can't just replace the current System.Windows.Forms.Application with a System.Windows.Application since my application heavily relies on this API and the two classes are widely incompatibles.

Is there a way to get the current System.Windows.Application ? Or a way to call BeginInvoke() on my System.Windows.Forms.Application ? Or am I deemed to write my own DIY system to delegate edition of the collection from the correct thread ?

like image 240
slaphappy Avatar asked Jul 02 '10 15:07

slaphappy


1 Answers

You should save a reference to SynchronizationContext.Current from the UI thread (perhaps in a static property) and use it instead of the Dispatcher.

In WPF, this will return a DispatcherSynchronizationContext; in WinForms, it will return a WindowsFormsSynchronizationContext.

You can then call Post on the saved SynchronizationContext, which is equivalent to BeginInvoke.

like image 154
SLaks Avatar answered Nov 02 '22 01:11

SLaks