打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
跨线程更新控件UI
private void btnCalculate_Click(object sender, EventArgs e)        {            Thread mythread = new Thread(Calculate);            mythread.IsBackground = true;        //設置為後臺線程,程式關閉后進程也關閉,如果不設置true,則程式關閉,此線程還在內存,不會關閉            mythread.Start();        }        private void Calculate()        {            this.Invoke(new Action(() => { progressBarWay.Visible = true; }));            Stopwatch stopwatch = Stopwatch.StartNew();            this.Invoke(new Action(() => { progressBarWay.Maximum = 500; }));            for (int i = 0; i < 500; i++)            {                Thread.Sleep(5);                this.Invoke(new Action(() => { progressBarWay.Value = i; }));            }            this.Invoke(new Action(() => { progressBarWay.Visible = false; }));            stopwatch.Stop();            long lSearchTime = stopwatch.ElapsedMilliseconds;            MessageBox.Show(lSearchTime.ToString() + "毫秒");        }

http://www.codeproject.com/Articles/269787/Accessing-Windows-Forms-Controls-across-Threads

delegate void ChangeMyTextDelegate(Control ctrl, string text);

This defines a reference to a method with a return type of "void" and takes two parameters: Control and String. Take a look at the following method that tries to update the text of a specified control.

Collapse | Copy Code
public static void ChangeMyText(Control ctrl, string text);{    ctrl.Text = text;}

This is all well and good, assuming that the thread that calls this method is the same thread that created the control. If not, we risk having our cars crash into one another.

To counter this, we use the Control's "InvokeRequired" property and the delegate we defined a moment ago. The resulting code looks like this:

Collapse | Copy Code
delegate void ChangeMyTextDelegate(Control ctrl, string text);public static void ChangeMyText(Control ctrl, string text){    if (ctrl.InvokeRequired)    {        ChangeMyTextDelegate del = new ChangeMyTextDelegate(ChangeMyText);        ctrl.Invoke(del, ctrl, text)    }    else    {        ctrl.Text = text;    }}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【Unity3D之获取某个方法执行的时间】
泛型的性能优势
浅谈C#中常见的委托
RS232 using thread-safe calls to Windows Forms controls - The Code Project - System Programming
避免InvokeRequired - jacky的日志 - 网易博客
c#多线程更新窗口(winform)GUI的数据
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服