.NET Dispatcher, for .NET Core?

It's not built-in, but my AsyncContext and AsyncContextThread types are available in a library that would fit your need.

AsyncContext takes over the current thread:

AsyncContext.Run(async () =>
{
  ... // any awaits in here resume on the same thread.
});
// `Run` blocks until all async work is done.

AsyncContextThread is a separate thread with its own AsyncContext:

using (var thread = new AsyncContextThread())
{
  // Queue work to the thread.
  thread.Factory.Run(async () =>
  {
    ... // any awaits in here resume on the same thread.
  });
  await thread.JoinAsync(); // or `thread.Join();`
}

AsyncContext provides a SynchronizationContext as well as a TaskScheduler/TaskFactory.


With .NET Core 3.0 you can now use Dispatcher class, but it will work only on Windows, and under netcoreapp3.0 TFM, so you cannot deploy your application on Linux or Mac.

You should add to your CSharp project following parameter

<PropertyGroup>
   ...
   <UseWPF>true</UseWPF>
   ...
</PropertyGroup>

and then you can use System.Windows.Threading.Dispatcher in your application.


Just as reference: You can do like both answers of codevision and JBSnorro:

Edit .csproj file manually. The project file should look like something similar to this (For Core 3.1 use 3.1 instead of 3.0):

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <UseWPF>true</UseWPF>
    </PropertyGroup>
</Project>

If the project is unloaded, use Reload Project from the content menu.

Note: UseWPF should be added but also the "Project Sdk" type should be modified.

Tags:

C#

.Net

.Net Core