简体   繁体   中英

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!

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();
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM