为什么不能在用户控件构造函数中启动线程? [英] Why can't I start a thread within a user control constructor?

查看:116
本文介绍了为什么不能在用户控件构造函数中启动线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道这是一种不好的做法.这已经变成了更多的需要了解"的练习,然后变成了最佳做法.

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.

我有一个从主Winform的构造函数初始化的用户控件.在该USerControl中,我试图启动一个保持活动的线程

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.

推荐答案

这是我的代码:

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

这篇关于为什么不能在用户控件构造函数中启动线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆