为什么我不能在用户控件构造函数中启动一个线程?

时间:2014-01-21 21:44:21

标签: c# multithreading winforms user-controls

首先,我知道这是不好的做法......这已经变成了一个“需要知道”的练习,然后是最佳练习练习。

我有一个usercontrol,它是从主winform的构造函数初始化的。在那个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();
    }

每当我这样做时,处理器不会在设计师内部触发,也不会发生事件。

只是不启动线程,处理器会触发。再说一遍......我知道这是不好的做法,但试图弄清楚为什么这不起作用。

1 个答案:

答案 0 :(得分: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();
    }
}