我的程序使用ShowDialog函数显示一个自定义对话框(我使用New构造函数创建此表单),但是当我的程序在对话框中等待输入时,我的程序继续运行其他代码,(我假设从其他消息启动),但我仍然无法找到关于此的好信息,所以除了这个主题之外,任何人都有关于此的参考),并且到达同一点,在该点显示对话框并显示它.所以我最终得到了大量的对话框.
我的目标是防止过多的对话框.如果程序到达此对话框启动点,我希望它等待/暂停,直到第一个对话框完成.
我考虑过线程解决方案,后台工作者,各种想法,但它们似乎使事情变得复杂,我实际上并没有修复它.
有谁知道如何防止这种情况发生?
非常感谢您的帮助.
谢谢
解决方法
此外,更改代码以打开模式对话框窗口,其中父窗口必须是所有者.模态对话框窗口将停止执行并阻止父窗口处理用户输入(这可能导致此行为).
编辑
根据您的评论,我收集到您有几个无法控制的线程,并且您希望一次一个线程来访问消息框代码.使用线程时,有几个可用的同步原语.扩展它们每个都需要一本书(你可以尝试Concurrent Programming on Windows,这本书在其结构中有一些缺陷时是彻底的),知道正确的一本书需要你的代码知识.
也就是说,您可能希望使用Mutex执行类似下面的操作,这至少会阻止其他线程访问代码(意味着:它会将它们置于挂起状态,直到Mutex被释放).如果要阻止弹出框显示多次,请添加一个静态布尔标志变量(或在弹出窗体“仅显示一次”上添加一个复选框). Mutex plus flag解决了两个问题:只有一个线程会运行该代码,代码只会运行一次.
// as static class variable,create a mutex private static Mutex dialogMutex = new Mutex(); // a static flag preventing the dialog box to show more than once // (you may wish to resolve this differently,depending on req's) private static boolean dialogIsShownOnce = false; public static void ShowDialogBox() { // Wait until it is safe to enter,this makes the current thread // the exclusive user of this code and other threads may only enter // after the current thread finishes. dialogMutex.WaitOne(); // depending on your requirements,you may not want this // must come _after_ WaitOne to prevent entering before another // thread that entered hasn't yet changed this variable if(dialogIsShownOnce) return; // show your dialog box as a modal box // if you are unsure: add a breakpoint just after the ShowDialog // it should only be hit _after_ you dismiss the dialog box yourForm.ShowDialog(); // set the flag,or the counter,or whatever you wish: dialogIsShownOnce = true; // Release the Mutex,this will remove the "roadblock" and allow // other threads to enter this piece of code dialogMutex.ReleaseMutex(); }
上面的代码未经过测试,应该被视为如何解决此问题的提示.有很多方法可以解决这个问题,但我认为上述方法可能正是您所需要的.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。