2014-01-21 70 views
1

首先,我知道这是不好的做法......这已经变成了更多的“需要知道”练习,然后在这一点上进行最佳练习练习。为什么我无法在用户控件构造函数中启动线程?

我有一个usercontrol从主winform的构造函数初始化。在该用户控件,我想开始保持活跃线程

public TestControl() 
    { 
     InitializeComponent(); 

     this.Disposed += Dispose; 

     // Start the keep alive Thread 
     _keepAliveThread = new Thread(
      () => 
      { 
       while (true) 
       { 
        Thread.Sleep(60000); 
        try 
        { 
         _service.Ping(); 
         Trace.WriteLine("Ping called on the Service"); 
        } 
        catch 
        { 
         Trace.WriteLine("Ping failed"); 
        } 
       } 
      }); 
     _keepAliveThread.Start(); 
    } 

每当我做到这一点,处置不设计者内火我也不让该事件。

只是不启动线程,处置火灾。再次...我知道这是不好的做法,但试图弄清楚为什么这是行不通的。

+0

你能按你的意思是“处置不设计者内火”澄清?你如何在没有运行的情况下检查它?我没有看到'Output'窗口中的任何内容表明它将从设计器中丢弃。 – Erik

回答

1

这里是我的代码:

public partial class SillyControl : UserControl 
{ 
    Thread backgroundThread; 
    Service service = new Service(); 

    public SillyControl() 
    { 
     InitializeComponent(); 

     this.Disposed += delegate { Trace.WriteLine("I been disposed!"); }; 

     backgroundThread = new Thread(argument => 
     { 
      Trace.WriteLine("Background ping thread has started."); 

      while (true) 
      { 
       Thread.Sleep(5000); 
       try 
       { 
        service.Ping(); 
        Trace.WriteLine("Ping!"); 
       } 
       catch (Exception ex) 
       { 
        Trace.WriteLine(string.Format("Ping failed: {0}", ex.Message)); 
       } 
      } 
     }); 

     backgroundThread.IsBackground = true; // <- Important! You don't want this thread to keep the application open. 
     backgroundThread.Start(); 
    } 
} 
+0

,似乎也没有工作。其实,我相信语法也是不正确的。 _service期望是Thread构造函数的一个int。 – AndySousa

+0

@AndySousa我已经编辑了语法,现在进一步调查,我打开了VS。 – Erik

+0

我刚刚更新了它,现在就进行测试。处置仍然没有得到调用,应用程序不会退出。任何其他想法? – AndySousa

相关问题