Why can't I start a thread within a user contr

2019-08-07 09:12发布

问题:

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. In that USerControl, I am trying to start a keep alive thread

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.

回答1:

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();
    }
}