我的场景如下:
应用程序加载和永远不会改变的数据的缓存开始,为此我做5批线程来调用WCF服务。
如果服务停止,我会弹出一个告知用户存在通信错误并询问他是否要重试或取消操作(这个逻辑发生在进行服务调用的线程内,这不是关心/知道任何其他正在运行的线程)。
由于我正在同时拨打5个电话并且服务已关闭,因此我会连续5次询问是否要重试该操作或取消该操作。
我想要做的是:因为我显示相同的问题只询问用户一次并将相同的结果返回给所有等待的线程。关于如何实现这一点的任何想法?这听起来是一个坏主意,所以我也愿意听到其他方法来实现相同的行为。
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());
}
}
谢谢!
答案 0 :(得分:1)
只需缓存对话框结果并将其提供给所有其他对话框(下面的代码可能需要一些调整,因为我在记事本中写了它):
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();
}
}
}
答案 1 :(得分:0)
在这种情况下,您必须使用带锁定的静态类/方法。但是有额外的逻辑处理用户答案并在解锁后将其返回到其他线程而不再显示弹出窗口。