wpf-notifyicon icon indicating copy to clipboard operation
wpf-notifyicon copied to clipboard

`TaskbarIcon.Dispose` throws exception if not called from application's main thread

Open jhinder opened this issue 2 years ago • 0 comments

The Dispose method of TaskbarIcon is not thread-safe, it can only be called from the WPF application's main thread.

This should either be documented, or the implementation should be made safe e.g. by making use of the Application instance's Dispatcher.

Version: 1.1.0

Steps to reproduce:

  • Create a WPF Application project.
  • Add a button with a Clicked handler to the main window.
  • Add this code to the handler:
    var taskbarIcon = new TaskbarIcon();
    var t = new Thread(() =>
    {
        taskbarIcon.Dispose();
    });
    t.Start();
    
  • Run the app and click the button

Result

System.InvalidOperationException: "The calling thread cannot access this object because a different thread owns it."

Callstack:

 	WindowsBase.dll!System.Windows.Threading.Dispatcher.VerifyAccess()	Unknown
 	WindowsBase.dll!System.Windows.Threading.DispatcherObject.VerifyAccess()	Unknown
 	PresentationFramework.dll!System.Windows.Application.Exit.remove(System.Windows.ExitEventHandler value)	Unknown
 	Hardcodet.NotifyIcon.Wpf.dll!Hardcodet.Wpf.TaskbarNotification.TaskbarIcon.Dispose(bool disposing)	Unknown
 	Hardcodet.NotifyIcon.Wpf.dll!Hardcodet.Wpf.TaskbarNotification.TaskbarIcon.Dispose()	Unknown
>	TrayIconThreadsafety.dll!TrayIconThreadsafety.MainWindow.Button_Click.AnonymousMethod__0() Line 36	C#
 	System.Private.CoreLib.dll!System.Threading.Thread.StartHelper.Callback(object state)	Unknown
 	System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state)	Unknown
 	System.Private.CoreLib.dll!System.Threading.Thread.StartCallback()	Unknown

jhinder avatar Jan 26 '23 09:01 jhinder