bezzad / Downloader

Fast, cross-platform and reliable multipart downloader with asynchronous progress events for .NET applications.
MIT License
1.25k stars 193 forks source link

The calling thread cannot access this object because another thread owns it #143

Closed 593172440 closed 5 months ago

593172440 commented 1 year ago

In .net framework 4.8 WPF I New Create UserControl Name "Loading" And apply it Downloader . In another xaml Grid.Children.Add(Loading).Unable to close after download is complete. prompt: System.InvalidOperationException:“The calling thread cannot access this object because another thread owns it。” Ask how to end this object in the loading interface

bezzad commented 1 year ago

When using WPF or another UI framework, it is not possible to directly access the main thread (UI thread) from another thread. Once your downloads are complete and you resume the await task with the result, the current thread may not be the main thread due to the Downloader running scenarios. Therefore, to call UI elements like Grid, you must use the Dispatcher, as shown in the code below:

Grid.Dispatcher.Invoke(new Action(() => Grid.Children.Add(Loading)));

This is a .Net thread management control. For more information, please refer to the following link:

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/threading-model?redirectedfrom=MSDN&view=netframeworkdesktop-4.8