简体   繁体   中英

Getting CoreDispatcher in WinForms Classic Desktop app

I have a C# WinForms app that scans for bluetooth devices on a background thread. When it is time to connect to a device, it must call the following method, that must be called on a UI thread:

 var btDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);

I understand that the way you do this is by encapsulating the above in a async method like ConnectToBluetoothDevice and calling it like this:

dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ConnectToBTDevice(args));

So far so good. My problem is that I cannot get a reference to a CoreDispatcher instance so I can make the above call. I have tried a number of ways:

  1. Repeatedly calling:

     try { dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher; } catch (System.InvalidOperationException e) { Console.WriteLine("Cannot get dispatcher yet"); } 

    The above always falls to the catch block, long after launching the app.

  2. Registering for a callback to the Form.Shown callback and then trying to get an instance of the dispatcher from the current UI thread like this:

     var form = new Form1(); form.Shown += FormShown; Application.Run(form); ... private static void FormShown(Object sender, EventArgs e) { var window = CoreWindow.GetForCurrentThread(); if (window != null) { dispatcher = window.Dispatcher; } } 

    In this case, window is always null, which surprises me because the whole point of this callback is that it happens after the form window is shown. Shouldn't this callback be on the UI thread, and return its CoreWindow?

What am I missing here? How can I get a CoreDispatcher from a WinForms app?

Not all UWP API can be accessed from Classic Desktop applications.

You can refer to this MSDN link , which explains that only API's which have the DualApiPartition attribute can be called from a classic desktop app.

Look at the documentation for CoreDispatcher and you will notice that it does not support the DualApiPartition attribute.

Alternatively a classic desktop app can refer to the Dispatcher class which is accessible via WindowsBase.dll using the System.Windows.Threading namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM