SharonKo
SharonKo

Reputation: 619

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. 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.

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. Is that a proper way of closing a thread with a dialog?

Upvotes: 1

Views: 156

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

There are at least two major problems with the original example: running a new UI thread and aborting a thread. 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().

Upvotes: 2

Related Questions