Skip to content

DialogHost and Multithreading #2844

@JDeuker

Description

@JDeuker

Bug explanation

I have two UI Threads, both having a DialogHost Control.

At the moment I only get a System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it.' as soon I call Show() on DialogHost.

I tried different dialogIdentifier names, but without success. Then I looked at the code of DialogHost.cs at the method private static DialogHost GetInstance(object? dialogIdentifier).

I have two LoadedInstances, one for each Thread.
Everytime GetInstance gets called, the foreach loop will iterate through all instances and will call dialogInstance.Dispatcher.VerifyAccess(); which will obviously fail.
Wouldn't it be smarter to move the Dispatcher Verification into the if (Equals(dialogIdentifier, dialogInstance.Identifier))?
So that only on a matched dialogIdentifier the Thread is relevant?

private static DialogHost GetInstance(object? dialogIdentifier)
        {
            if (LoadedInstances.Count == 0)
                throw new InvalidOperationException("No loaded DialogHost instances.");
            List<DialogHost> targets = new();
            foreach (var instance in LoadedInstances.ToList())
            {
                if (instance.TryGetTarget(out DialogHost? dialogInstance))
                {
                    dialogInstance.Dispatcher.VerifyAccess();
                    if (Equals(dialogIdentifier, dialogInstance.Identifier))
                    {
                        targets.Add(dialogInstance);
                    }
                }
                else
                {
                    LoadedInstances.Remove(instance);
                }
            }
}

Version

4.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Waiting on feedbackAdditional information is needed. Stale items with this label may be closed.bug

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions