2

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!

2 Answers 2

1

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Teoman, where would be the best way to reset the dialogShown flag?
It is not thread safe it is best to reset it anywhere in the lock(this) { } block.
but then wouldnt it be always 'false' for the next incoming thread?
Well then use yet anoter private backing field like private int threadUsed = 0; and increment it in the lock() block and when it reaches 4, reset the flag.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.