[英]Form management in a multi-display application
I'm trying to figure out the best way to manage multiple forms in a C# application that uses dual-monitors. 我试图找出在使用双监视器的C#应用程序中管理多种表单的最佳方法。 The application starts to a "launchpad," which just gives the operator some quick information and a "GO" button. 该应用程序从“启动板”开始,该启动板仅向操作员提供一些快速信息和“ GO”按钮。 Pressing that button hides the launchpad and displays a form on each monitor in full-screen. 按下该按钮将隐藏启动板,并以全屏方式在每个监视器上显示一个表单。 I've tried to capture the relevant code here: 我试图在这里捕获相关代码:
private static List<Thread> _displays = new List<Thread>();
// "GO" button handler
private void OnClick(Object sender, EventArgs args) {
Launch(new Form1());
Launch(new Form2());
WaitForAllDisplays();
}
private static void Launch(Form form) {
Thread thread = new Thread(LaunchDisplay);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start(form);
_displays.Add(thread);
}
private static void LaunchDisplay(Object obj) {
Form display = obj as Form;
// [snip] logic to place form on correct monitor [/snip]
display.ShowDialog();
}
public static void WaitForAllDisplays() {
foreach (Thread thread in _displays) {
thread.Join();
}
}
It feels a little messy to leave the main thread blocked on this WaitForAllDisplays()
call, but I haven't been able to think of a better way to do this. 在此WaitForAllDisplays()
调用中保留主线程的感觉有点混乱,但是我还没有想到一种更好的方法来执行此操作。 Notice that Form1
and Form2
are independent of each other and never communicate directly. 请注意, Form1
和Form2
彼此独立,并且从不直接通信。
I considered using a counting semaphore to wait for all displays to close, but this is a little opposite of a traditional semaphore. 我考虑过使用计数信号量来等待所有显示关闭,但这与传统信号量有些相反。 Instead of executing when a resource becomes available, I want to block until all resources are returned. 我想在所有资源都返回之前阻塞,而不是在资源可用时执行。
Any thoughts on a better approach? 对更好的方法有什么想法吗?
At first I thought of this would work: 起初,我认为这会起作用:
You can use Events for example: 2 ManualResetEvent objects. 您可以使用事件作为示例:2个ManualResetEvent对象。 The main thread will wait on the events using WaitHandle.WaitAll and an array of 2 Mutexes. 主线程将使用WaitHandle.WaitAll和2个Mutexes数组等待事件。 Each thread gets a reference to 1 event and signals it when it's done (before it dies). 每个线程都会获得对1个事件的引用,并在事件完成时发出信号(在死亡之前)。
But then I figured you're better off using 2 mutexes instead and waiting on them. 但是后来我发现您最好使用2个互斥锁,然后等待它们。 This way if a thread is terminated abnormally without "signalling" (=Releasing the mutex) you'll get a AbandonedMutexException which you can and should handle. 这样,如果线程异常终止而没有“发出信号”(释放互斥锁),您将获得一个AbandonedMutexException,可以并且应该处理。 You can use AbandonedMutexException.MutexIndex to know which thread caused the exception. 您可以使用AbandonedMutexException.MutexIndex知道哪个线程导致了异常。
You can have a look at this answer to see how to handle the mutex and exception 您可以看一下这个答案 ,看看如何处理互斥体和异常
NOTE: 注意:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.