问题描述
|
我的高级场景如下:
应用程序加载和永不更改的数据缓存开始,为此,我分批处理了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());
}
}
谢谢!
解决方法
只需缓存对话框结果并将其提供给所有其他对话框,如下所示(下面的代码可能需要进行一些调整,如我在记事本中编写的那样):
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();
}
}
}
,在这种情况下,您必须使用带锁的静态类/方法。但是具有处理用户答案并在解锁后返回其他线程的附加逻辑,而无需再次显示弹出窗口。