[英]Why can't I start a thread within a user control constructor?
首先,我知道這是一個不好的做法……這已經變成了更多的“需要了解”練習,然后變成了最佳做法練習。
我有一個從主要winform的構造函數初始化的usercontrol。 在該USerControl中,我試圖啟動一個保持活動線程
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();
}
每當執行此操作時,布置都不會在設計器內觸發,也不會得到事件。
根本不啟動線程,則觸發處理。 再說一次……我知道這是一個不好的做法,但是試圖弄清楚為什么這是行不通的。
這是我的代碼:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.