dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
21.89k stars 1.69k forks source link

Some Essentials APIs crash when using multi-window #5536

Open mattleibow opened 2 years ago

mattleibow commented 2 years ago

Description

Most of the sensors (but some others) are using an incorrect way of marshalling the events to the main thread. They pick the active window, but this is incorrect because if you have multiple windows and then try update another window, there is a marshalling error.

Steps to Reproduce

  1. Create a new window on the default thread
  2. Create a new window on a new thread
  3. Start listening to accelerometer on both windows
  4. Update a label on each window in the event
  5. One window (the non-active window) will throw an exception

Start a new window in a new thread like this:

var thread = new Thread(() =>
{
    Microsoft.UI.Xaml.Application.Start(async (p) =>
    {
        var dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();
        var syncContext = new Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext(dispatcherQueue);
        SynchronizationContext.SetSynchronizationContext(syncContext);

        Application.Current.OpenWindow(new Window(new MultiWindowPage()));
    });
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

Version with bug

Preview 14 (current)

Last version that worked well

Unknown/Other

Affected platforms

Windows

Affected platform versions

All

Did you find any workaround?

No response

Relevant log output

No response

mattleibow commented 2 years ago

Working on getting this done. Found some interesting things that happen: resources are not shared - sort of expected tbh

Need to get the recommendations from the WinUI team. Repro here: https://github.com/mattleibow/WinUIMultiThreadResources

mattleibow commented 2 years ago

Moving this to a later thing because multi-window for multi-threads is no longer supported in 1.0.x as the main way is now on a single thread. This will get added, but not sure of dates exactly.

From the WinUI team:

multi-window only works for single thread, we still don’t support multiple windows on multiple threads. I think when we took out the block on multi-window we should have added a block for multi-threaded.

So as of right now, this is not a supported option and about the multi-threaded resources:

It’s something we need to design, I don’t think we can stick with the way Xaml behaves in UWP today.

mattleibow commented 1 year ago

This is directly related to work here: https://github.com/dotnet/maui/issues/5534