Skip to content

dialog host task was canceled issue #3824

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
AmeerMansour opened this issue Mar 28, 2025 · 6 comments
Open

dialog host task was canceled issue #3824

AmeerMansour opened this issue Mar 28, 2025 · 6 comments
Labels
bug evaluation required Items is pending review or evaluation by the team Stale Issues and PRs that have not had activity for a while are marked with this label. Waiting on feedback Additional information is needed. Stale items with this label may be closed.

Comments

@AmeerMansour
Copy link

Bug explanation

Image

I am using material design in developing addins for 3d softaware so I am using host the first time i uses dialog it shows correctly but when i end the host and start new one, it throw this exception !

how to fix this error ?

Version

5.2.1

@AmeerMansour AmeerMansour added bug evaluation required Items is pending review or evaluation by the team labels Mar 28, 2025
@AmeerMansour
Copy link
Author

even this throw exception

var rrr= DialogHost.GetDialogSession (_mainWindow.GetDialogIdentifier());

@AmeerMansour
Copy link
Author

AmeerMansour commented Mar 29, 2025

Image

this is stack trace

Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in mscorlib.dll
2025-03-29 15:21:10 [FTL] System.AppDomain: Domain unhandled exception
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Windows.Threading.DispatcherOperation.Wait(TimeSpan timeout)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherOperation operation, CancellationToken cancellationToken, TimeSpan timeout)
at System.Windows.Threading.Dispatcher.Invoke[TResult](Func1 callback, DispatcherPriority priority, CancellationToken cancellationToken, TimeSpan timeout) at MaterialDesignThemes.Wpf.DialogHost.GetInstance(Object dialogIdentifier) at MaterialDesignThemes.Wpf.DialogHost.<Show>d__30.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at BIMDoers.Common.UI.Services.MaterialDesignDialogService.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at ManagementTools.FilteredElementSelector.UI.UI.ViewModels.ElementSelectorsViewModel.<ViewViewsFilters>d__57.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at CommunityToolkit.Mvvm.Input.AsyncRelayCommand.<AwaitAndThrowIfFailed>d__40.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at BIMDoers.Revit.Toolkit.External.Commands.MultiThreadExternalCommand.<>c__DisplayClass0_0.<Execute>b__2() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() Application Insights Telemetry: {"name":"AppExceptions","time":"2025-03-29T02:21:10.3919752Z","iKey":"0a3f2320-f8c2-4702-ae7b-c62046e38c00","tags":{"ai.application.ver":"2024.0.0.0","ai.device.type":"Filtered Element Selector","ai.device.osVersion":"Revit 2024","ai.device.model":"FilteredElementSelector","ai.cloud.roleInstance":"AmeerLaptop","ai.session.id":"2e7ab0bb-d3ca-47e9-be63-cbe41f5d8522","ai.user.id":"[email protected]","ai.operation.name":"Filtered Element Selector|FilteredElementSelector","ai.internal.sdkVersion":"il:2.23.0-29"},"data":{"baseType":"ExceptionData","baseData":{"ver":2,"exceptions":[{"id":61227003,"outerId":0,"typeName":"System.Threading.Tasks.TaskCanceledException","message":"A task was canceled.","hasFullStack":true,"parsedStack":[{"level":0,"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":1,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":2,"method":"System.Windows.Threading.DispatcherOperation.Wait","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":3,"method":"System.Windows.Threading.Dispatcher.InvokeImpl","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":4,"method":"System.Windows.Threading.Dispatcher.Invoke","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":5,"method":"MaterialDesignThemes.Wpf.DialogHost.GetInstance","assembly":"MaterialDesignThemes.Wpf, Version=5.2.1.0, Culture=neutral, PublicKeyToken=df2a72020bd7962a","line":0},{"level":6,"method":"MaterialDesignThemes.Wpf.DialogHost+<Show>d__30.MoveNext","assembly":"MaterialDesignThemes.Wpf, Version=5.2.1.0, Culture=neutral, PublicKeyToken=df2a72020bd7962a","line":0},{"level":7,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":8,"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":9,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":10,"method":"System.Runtime.CompilerServices.TaskAwaiter1.GetResult","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":11,"method":"BIMDoers.Common.UI.Services.MaterialDesignDialogService+d__3.MoveNext","assembly":"BIMDoers.Common.UI, Version=1.0.4.0, Culture=neutral, PublicKeyToken=null","line":0},{"level":12,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":13,"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":14,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":15,"method":"System.Runtime.CompilerServices.TaskAwaiter`1.GetResult","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":16,"method":"ManagementTools.FilteredElementSelector.UI.UI.ViewModels.ElementSelectorsViewModel+d__57.MoveNext","assembly":"ManagementTools.FilteredElementSelector.UI, Version=2024.0.0.0, Culture=neutral, PublicKeyToken=null","line":0},{"level":17,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":18,"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":19,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":20,"method":"CommunityToolkit.Mvvm.Input.AsyncRelayCommand+d__40.MoveNext","assembly":"CommunityToolkit.Mvvm, Version=8.4.0.0, Culture=neutral, PublicKeyToken=4aff67a105548ee2","line":0},{"level":21,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":22,"method":"System.Windows.Threading.ExceptionWrapper.InternalRealCall","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":23,"method":"System.Windows.Threading.ExceptionWrapper.TryCatchWhen","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":24,"method":"System.Windows.Threading.DispatcherOperation.InvokeImpl","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":25,"method":"System.Threading.ExecutionContext.RunInternal","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":26,"method":"System.Threading.ExecutionContext.Run","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":27,"method":"System.Threading.ExecutionContext.Run","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":28,"method":"MS.Internal.CulturePreservingExecutionContext.Run","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":29,"method":"System.Windows.Threading.DispatcherOperation.Invoke","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":30,"method":"System.Windows.Threading.Dispatcher.ProcessQueue","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":31,"method":"System.Windows.Threading.Dispatcher.WndProcHook","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":32,"method":"MS.Win32.HwndWrapper.WndProc","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":33,"method":"MS.Win32.HwndSubclass.DispatcherCallbackOperation","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":34,"method":"System.Windows.Threading.ExceptionWrapper.InternalRealCall","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":35,"method":"System.Windows.Threading.ExceptionWrapper.TryCatchWhen","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":36,"method":"System.Windows.Threading.Dispatcher.LegacyInvokeImpl","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":37,"method":"MS.Win32.HwndSubclass.SubclassWndProc","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":38,"method":"MS.Win32.UnsafeNativeMethods.DispatchMessage","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":39,"method":"System.Windows.Threading.Dispatcher.PushFrameImpl","assembly":"WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","line":0},{"level":40,"method":"BIMDoers.Revit.Toolkit.External.Commands.MultiThreadExternalCommand+<>c__DisplayClass0_0.b__2","assembly":"BIMDoers.Revit.Toolkit, Version=2024.0.6.0, Culture=neutral, PublicKeyToken=null","line":0},{"level":41,"method":"System.Threading.ExecutionContext.RunInternal","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":42,"method":"System.Threading.ExecutionContext.Run","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":43,"method":"System.Threading.ExecutionContext.Run","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0},{"level":44,"method":"System.Threading.ThreadHelper.ThreadStart","assembly":"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","line":0}]}],"severityLevel":"Critical","properties":{"DeveloperMode":"true","OriginalFormat":"Domain unhandled exception occurred","FormattedMessage":"Domain unhandled exception occurred","CategoryName":"System.AppDomain"}}}}
An unhandled exception of type 'System.Threading.Tasks.TaskCanceledException' occurred in mscorlib.dll
A task was canceled.

@corvinsz
Copy link
Member

@AmeerMansour I'm afraid I don't quite understand your problem.
I at first thought you wanted to do the following:

  1. Show some Dialog
  2. Close the first Dialog manually
  3. Show another (different) Dialog

Which would look something like this:

public partial class MyVM : ObservableObject
{
	public const string DIALOG_IDENTIFIER = "RootDialog";

	[RelayCommand]
	private async Task ShowDialogs()
	{
		// Intentionally not await this call so the 2nd dialog is shown automatically after 2 seconds
		DialogHost.Show(CreateTextBlock("content 1"), DIALOG_IDENTIFIER);
		await Task.Delay(2000);
		DialogHost.Close(DIALOG_IDENTIFIER);
		await DialogHost.Show(CreateTextBlock("content 2"), DIALOG_IDENTIFIER);
	}

	private static TextBlock CreateTextBlock(string text) =>
		new()
		{
			Text = text,
			Margin = new Thickness(16)
		};
}

However this works fine for me. Please provide more clear reproduction steps, or even better, a sample repo showcasing this bug.

@AmeerMansour
Copy link
Author

It is quite complex to replicate the system. I will try to be clearer on my scenario.

  1. I create a host using Microsoft.Extensions.Hosting and then starting it within a running application domain, as I am developing add-ins.
  2. Within this host, I launch a UI thread that opens the main window. When the user closes the main window, I dispose of the host.
  3. However, if the user requests the main window again, I recreate the host, but at that point, the dialog host fails to work.

@nicolaihenriksen
Copy link
Contributor

@AmeerMansour I have tried to replicate the scenario you describe, but I am not seeing the error, so I am probably doing something wrong compared to you. Perhaps you can elaborate a bit more.

Let me explain what I have done:

In the Main demo app of MDIX I have added a button on the start page. I have configured the Click event of that button to hit the following event handler:

private IHost? _host;

private void OpenDialogHostWindowButton_Click(object sender, RoutedEventArgs e)
{
    if (_host is { } oldHost)
    {
        oldHost.Dispose();
    }

    _host = CreateHostBuilder([]).Build();
    var launcher = _host.Services.GetRequiredService<DialogHostWindowLauncher>();
    launcher.LaunchDialogHostWindow(_host);
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddTransient<DialogHostWindowLauncher>();  // Also tried AddSingleton(); still works...
        });

This basically just creates a generic host where it adds a single service to the service collection, namely a DialogHostWindowLauncher. This is a type I have created to simply encapsulate your bullet 2 from above (launch a new UI thread within the host, and disposing the host when the dialog closes). The class is fairly simple like this:

internal class DialogHostWindowLauncher : IDisposable
{
    private DialogHostWindow? _window;

    public void LaunchDialogHostWindow(IHost host)
    {
        Thread newWindowThread = new(() =>
        {
            _window = new DialogHostWindow();
            _window.Closing += (_, __) => host.Dispose();
            _window.Show();
            System.Windows.Threading.Dispatcher.Run();
        });

        newWindowThread.SetApartmentState(ApartmentState.STA);
        newWindowThread.IsBackground = true;
        newWindowThread.Start();
    }

    public void Dispose()
    {
        if (_window is { } window)
        {
            window.Dispatcher.BeginInvoke(() => window.Close());
        }
    }
}

The dialog that it creates is just a simple Window which has Style="{StaticResource MaterialDesignWindow}", and a button that can show the dialog content set on the DialogHost:

<Window x:Class="MaterialDesignDemo.DialogHostWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:local="clr-namespace:MaterialDesignDemo"
        mc:Ignorable="d"
        Style="{StaticResource MaterialDesignWindow}"
        WindowStartupLocation="CenterScreen"
        Title="DialogHostWindow" Height="450" Width="800">
  <materialDesign:DialogHost ApplyBlurBackground="True" CloseOnClickAway="True">
    <materialDesign:DialogHost.DialogContent>
      <StackPanel Margin="50">
        <TextBlock Text="This is some text in a DialogHost" />
        <Button VerticalAlignment="Bottom" HorizontalAlignment="Center" Content="Close Dialog" Margin="10" Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}" />
      </StackPanel>
    </materialDesign:DialogHost.DialogContent>
    <Grid>
      <Button VerticalAlignment="Bottom" HorizontalAlignment="Center" Content="Show Dialog" Margin="10" Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}" />
    </Grid>
  </materialDesign:DialogHost>
</Window>

With this setup, I can continuously open the window in its own UI thread, click the button and thus show the dialog in the newly opened window. Works both with a transient launcher as well as a singleton launcher.

My guess is that your code for creating the host and/or creating the UI thread is somewhat different than this; could you help me better understand how your code looks? Thanks.

@nicolaihenriksen nicolaihenriksen added the Waiting on feedback Additional information is needed. Stale items with this label may be closed. label Apr 14, 2025
Copy link
Contributor

This issue is marked stale because it has been open 30 days with no activity. Remove stale label or update the issue, otherwise it will be closed in 14 days.

@github-actions github-actions bot added the Stale Issues and PRs that have not had activity for a while are marked with this label. label May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug evaluation required Items is pending review or evaluation by the team Stale Issues and PRs that have not had activity for a while are marked with this label. Waiting on feedback Additional information is needed. Stale items with this label may be closed.
Projects
None yet
Development

No branches or pull requests

3 participants