2012-08-05 35 views
0

我正在用LinuxMint和MonoDevelop开发C#应用程序。
我写了下面的代码,
Mono中的多个Windows应用程序的bug

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 
using System.Threading; 
using System.Diagnostics; 

namespace TestProgram 
{ 
    public static class Program 
    { 
     public static int count = 0; 
     static object locker = new object(); 

     const int limit = 10; 

     [STAThread] 
     static void Main() 
     { 
      for(int i = 0; i < Program.limit; ++i) 
      { 
       Action item =() => Program.RunForm(); 
       item.BeginInvoke((a) => item.EndInvoke(a), null); 
       Thread.Sleep(1000); 
      } 

      while(true) 
      { 
       Thread.Sleep(1000); 
       if(Program.count == 0) 
        break; 
      } 

      return; 
     } 

     static void RunForm() 
     { 
      lock(Program.locker) { 
       Program.count += 1; 
      } 

      Application.EnableVisualStyles(); 
      Application.Run(new Form()); 

      lock(Program.locker) { 
       Program.count -= 1; 
      } 
     } 
    } 
} 

在DOTNET,程序工作正常。 10个窗口显示正确。
在单声道中,程序崩溃,没有托管异常。
当出现第2,第3或更晚的窗口时,它突然崩溃。

这是单声道的错误吗?或者代码错了?
为什么行为不同?

(请原谅我糟糕的英语。)

+2

使用'Thread.Sleep'本身就是一个bug。 – 2012-08-05 17:02:35

+0

下一次请确保您在询问之前做一些调查,http://www.mono-project.com/FAQ:_Winforms。如果任何问题如此明显,它必须是一个报告的错误或已知的错误。 – 2012-08-06 02:47:56

回答

5

该代码应该(和意志,对操作系统和.NET的一些组合)在Windows上破上的Microsoft .NET为好。您应该只在单个线程上创建表单,绝对不应多次拨打Application.Run()

+0

不,调用Application.Run和使用多线程本身是完全安全的。当然,每个单独的控制都必须独立运行。 – usr 2012-08-05 22:42:44

+0

+1,你应该链接到Mono WinForms FAQ,http://www.mono-project.com/FAQ:_Winforms Item 2明确指出这是设计。 – 2012-08-06 02:46:44