专注于高品质PHP技术等信息服务于一体 [STIEMAP] [RSS]

百度提供的广告:
c#
当前位置:首页 > 技术文档 > c# >  > 
c# 多线程子线程修改UI死机
在C# 多线程中,不可以直接修改主窗体控件的属性修改。
可以使用 this.Invoke(new Action<string> (tipMessage),"hello");
namespace 多线程弹窗
{
    public partial class Form1 : Form
    {
       

        public Tip tip = new Tip();
        public Rectangle rect = SystemInformation.VirtualScreen;
        public int showTipTime = 0;
        public Thread mainThre = null;
        public Thread tipThre = null;

        public Form1()
        {
            InitializeComponent();
            mainThre = new Thread(mainThread);
            tipThre = new Thread(tipThread);
            mainThre.IsBackground = true;
            tipThre.IsBackground = true;
            mainThre.Start();
            tipThre.Start();
        }

        public void tipMessage(string msg)
        {
            Point point = new Point(rect.Width - 280, rect.Height - 200);
            tip.PointToScreen(point);
            tip.Location = point;
            tip.setMessage(msg);
            showTipTime = 440;//停留2秒*/
            tip.Show();
        }

        public void mainThread()
        {
            while (true)
            {
                if (0 < flag)
                {
                    this.Invoke(new Action<string> (tipMessage),"hello");
                }
                Thread.Sleep(5000);
            }
        }

        public void tipThread()
        {
            while (true)
            {
                if (0 < showTipTime)
                {
                    showTipTime--;
                    if (300 <= showTipTime)
                    {
                        tip.Location = new Point(tip.Location.X, tip.Location.Y - 1);
                    }
                }
                Thread.Sleep(10);
            }
        }
    }
}

在多线程中,也不是完全不可以修改主UI的控件,只要修改所用的时间非常短也是可以的,如果是费时的调用,就会造成子线程控件死机。