简体   繁体   English

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

[英]Why can't I start a thread within a user control constructor?

First off, I know this is bad practice... this has turned into more of a "NEED TO KNOW" exercise then a best practices exercise at this point. 首先,我知道这是一个不好的做法……这已经变成了更多的“需要了解”练习,然后变成了最佳做法练习。

I have a usercontrol which is initialized from the constructor of the main winform. 我有一个从主要winform的构造函数初始化的usercontrol。 In that USerControl, I am trying to start a keep alive thread 在该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();
    }

Whenever I do this, the dispose does not fire within the designer nor do I get the event. 每当执行此操作时,布置都不会在设计器内触发,也不会得到事件。

Simply not starting the thread, the dispose fires. 根本不启动线程,则触发处理。 Again... I know this is bad practice, but trying to figure out why this just doesn't work. 再说一次……我知道这是一个不好的做法,但是试图弄清楚为什么这是行不通的。

Here is my code: 这是我的代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM