How to detect if on foreground thread or not in Core from class assembly?

Richard Haggard 6 Reputation points
2021-05-05T14:46:39.803+00:00

I’m having problems with determining if the current thread is FG or BG. The standard is to use Application.Current.Dispatcher.CheckAccess but that is difficult in a class library in a Core environment.

In Framework, this is easily accomplished by including a reference to the PresentationFramework class assembly and then using something like this:

public static void UIThread( Action action )
{
    if (Application.Current.Dispatcher.CheckAccess())
    {
        // On FG thread. Can directly invoke the action.
        action.Invoke();
    }
    else
    {
        // On BG thread. Must do an invoke to get on FG.
        Application.Current.Dispatcher.Invoke( action );
    }
}

I'm in a Core framework class library and need to know if the code is executing on a foreground thread or in the background and, if BG, then it would need to make the transition to FG. I attempted to add PresentationFramework to my class library module. Hmm. Visual Studio doesn't seem to want me to do that.
Add Reference doesn't work the same. It doesn't have the same ability to add PresentationFramework.dll to the references. Similarly, managing Nuget Packages doesn't really seem to want to insert a reference to PresentationFramework.dll.

Hours later, I've given up on discovering the secret for myself. Time to ask the community. So, how does one figure out if the current thread is FG or not in Core when in a class library DLL module?

Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-05-05T18:08:47.69+00:00

    In case of Core projects, Visual Studio shows an additional command in Project menu: “Edit Project File”. Here you can view and edit some of the settings according to documentation. Try adjusting your Class Library project to include the next lines:

    <PropertyGroup>
       <TargetFramework>net5.0-windows</TargetFramework>
       <UseWPF>true</UseWPF>
       . . .
    </PropertyGroup>
    

    (Specify the framework that is used by your main WPF project).

    Then the CheckAccess function should be available.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.