Sebastian Piu
Sebastian Piu

Reputation: 8008

Showing single dialog from multiple threads

My scenario at a high level is the following:

Application loads and caching of data that never is going to change starts, for this I do batches of 5 threads that do a call to a WCF service.

If the service is down I'll get a popup informing the user that there was a communication error and ask whether he wants to retry or cancel the operation (this logic happens inside the thread that is making the service call, which doesn't care/know of any other running threads).

As I'm doing 5 calls at once and the service is down, I'll get asked 5 consecutive times about if I want to retry the operation or cancel it.

What I'd like to do is: as I'm showing the same question only ask the user once and return the same result to all waiting threads. Any ideas on how to achieve this? It sounds as a bad idea so I'm also open to hear other ways to achieve the same behaviour.

public string Show(string key, Action<DialogBuilder> action)
{
    lock (this) //now 4 threads are waiting here
    {       
         //marshal the dialog to the UI thread  
         return _dispatcher.Send(() => new MyDialogForm().ShowDialog()); 
    }
}

Thanks!

Upvotes: 2

Views: 283

Answers (2)

Teoman Soygul
Teoman Soygul

Reputation: 25742

Just cache the dialog result and provide it to all other dialogs like this (below code may need some tweaking as I wrote it in notepad):

private DialogResult threadedDialogResult;
private bool dialogShown;

public string Show(string key, Action<DialogBuilder> action)
{
    lock (this) //now 4 threads are waiting here
    {
        if (!dialogShown)
        {
            //marshal the dialog to the UI thread  
            return _dispatcher.Send(() => { dialogShown = true; this.threadedDialogResult = new MyDialogForm().ShowDialog(); });
        }
        else
        {
            // Use the cached dialog result as we know it was shown
            return threadedDialogResult.ToString();
        }
    }
}

Upvotes: 1

vityanya
vityanya

Reputation: 1176

You have to use static class/method with lock in this case. But with additional logic that handle user answer and return it to other threads after unlock without showing the popup again.

Upvotes: 0

Related Questions