C# 在线程-C中关闭WPF#

C# 在线程-C中关闭WPF#,c#,wpf,multithreading,dialog,C#,Wpf,Multithreading,Dialog,我有一个显示对话框的线程。我之所以使用线程,是因为我希望在主线程继续执行一些繁重的工作时立即显示对话框(因此我使用ShowDialog())。当主线程使用“heavy”函数完成时,我希望对话框停止显示 这是我正在使用的代码: Thread searchingAlertThread = (new Thread(() => { SearchingAlert searchingAlert = new SearchingAlert(); try { searchin

我有一个显示对话框的线程。我之所以使用线程,是因为我希望在主线程继续执行一些繁重的工作时立即显示对话框(因此我使用
ShowDialog()
)。当主线程使用“heavy”函数完成时,我希望对话框停止显示

这是我正在使用的代码:

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
searkingalert
是一个WPF窗口对话框,显示带有动画gif的
TextView
ImageView

问题是,有时当多次调用此函数时(如果未找到任何设备),将不会显示
ImageView
,更重要的是,不会抛出
ThreadAbortException

这是通过对话框关闭线程的正确方法吗?

原始示例至少存在两个主要问题:运行新的UI线程和中止线程。请尝试以下方法:

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

现在还不清楚什么是
client
,但是如果它提供了一个异步版本的
DiscoverDevices()
方法,你应该等待它,而不是使用
Task.Run()

使用
Invoke()
来关闭对话框。@SLaks抱歉误解,但这是WPF。。。我已经编辑了问题Don't use ShowDialog。如果你只需要打开一个线程来创建一个窗口而不是另一个窗口,这就意味着有问题了。。。为什么不打开一个窗口或创建一个显示进度的usercontrol呢?谢谢SharonKo在我的回答中修复了代码。我很惊讶你的编辑被其他SO评论员拒绝了。这是一个很好的编辑,我已经继续并安装了您提出的更改。