[英]Closing a WPF within Thread - C#
I have a thread that shows a dialog. 我有一个显示对话框的线程。 The reason I use a thread for this is because I want the dialog to show immediately (so I use ShowDialog()
)) while the main thread continue do some heavy work. 我之所以使用线程是因为我希望对话框在主线程继续执行大量工作的同时立即显示(所以我使用ShowDialog()
)。 When the main thread finish with the "heavy" function, I want the dialog to stop showing. 当主线程完成“重载”功能后,我希望对话框停止显示。
This is the code i'm using: 这是我正在使用的代码:
Thread searchingAlertThread = (new Thread(() =>
{
SearchingAlert searchingAlert = new SearchingAlert();
try {
searchingAlert.ShowDialog();
} catch (ThreadAbortException) { // Thrown when the thread is aborted
searchingAlert.Close();
}
}));
searchingAlertThread.SetApartmentState(ApartmentState.STA);
searchingAlertThread.Start(); // Starts the thread
BluetoothDeviceInfo[] devices = client.DiscoverDevices(); // Takes 15 seconds
searchingAlertThread.Abort(); // Stops the thread
The searchingAlert
is WPF window dialog that shows TextView
and ImageView
with animated gif. searchingAlert
是WPF窗口对话框,显示带有动画gif的TextView
和ImageView
。
The problem is, that sometimes when this called is called more then once (in case it didn't find any devices), the ImageView
is not shown, and more important, the ThreadAbortException
isn't thrown. 问题是,有时当多次调用此调用时(如果找不到任何设备),将不显示ImageView
,更重要的是,不会引发ThreadAbortException
。 Is that a proper way of closing a thread with a dialog? 这是用对话框关闭线程的正确方法吗?
There are at least two major problems with the original example: running a new UI thread and aborting a thread. 原始示例至少存在两个主要问题:运行新的UI线程和中止线程。 Try this instead: 尝试以下方法:
SearchingAlert searchingAlert = new SearchingAlert();
BluetoothDeviceInfo[] devices = null;
searchingAlert.Loaded += async (sender, e) =>
{
devices = await Task.Run(() => client.DiscoverDevices());
searchingAlert.Close();
};
searchingAlert.ShowDialog();
// Use the devices array here
It's not clear what client
is, but of course if it offers an async version of the DiscoverDevices()
method, you should just await on that instead of using Task.Run()
. 目前尚不清楚什么是client
,但是如果它提供了DiscoverDevices()
方法的异步版本,则当然应该等待它,而不是使用Task.Run()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.