Захват основного потока SynchronizationContext или Dispatcher из библиотеки

У меня есть библиотека C #, в которой я хотел бы иметь возможность отправлять / отправлять работы на & quot; main & quot; Пользовательский поток (если таковой существует). Эта библиотека может использоваться:

A winforms application A native application (with UI) A console application (with no UI)

В библиотеке я хотел бы захватить что-то (SynchronizationContext, Dispatcher, Task Scheduler или что-то еще) во время инициализации, что позволит мне (позднее) отправить / опубликовать работу в главном потоке (если основной поток имеет эту возможность - то есть он имеет насос сообщений). Например, библиотека хотела бы установить некоторый пользовательский интерфейс Winforms в главном потоке, если и только если основное приложение имеет возможность для меня добраться до основного потока.

Вещи, которые я пробовал:

A SynchronizationContext: Capturing this works fine for a Winforms application (a WindowsFormsSynchronizationContext will be installed as the Current SynchronizationContext. This also works fine for the console app--since I can detect that the Current SynchronizationContext is null (and thus, know that I don't have the ability to send/post work to the main thread). The problem here is the native UI application: It has the ability (i.e. it has a message pump), but the Current Synchronization context is null and thus I can't differentiate it from the Console app case. If I could differentiate, then I could simply install a WindowsFormsSynchronizationContext on the main thread, and I'm good to go. A Dispatcher: Capturing this using Current creates a new SynchronizationContext. Thus, in all situations I will get back a Dispatcher. However, for a Console app, using Dispatcher.Invoke from a background thread will hang (as expected). I could use Dispatcher.FromThread (which doesn't create a Dispatcher for the thread if one doesn't exist). But the native UI application will return a null Dispatcher using this method, and so then I'm, again, stuck not being able to distinguish the UI application from the console application. A TaskScheduler: I could use FromCurrentSynchronizationContext. This has the same problems as the SynchronizationContext. I.e. Before calling FromCurrentSyncronizationContext, I'd have to check if the Current SynchronizationContext is null (which will be the case for the Console app and the native ui application). So, again I can't distinguish the native ui application from the console application.

Я, конечно, мог бы указать пользователю моей библиотеки, является ли это приложение пользовательского интерфейса, когда они вызывают мойInitialize метод, но я надеялся избежать этого осложнения для пользователя библиотеки, если это возможно.

Ответы на вопрос(4)

Ваш ответ на вопрос