Winform 子线程更新 控件

来源:互联网 发布:安全炒股软件 编辑:程序博客网 时间:2024/06/03 13:39

大姐做了个生成MD5码的工具,用来做游戏资源的对比更新。让我给加个多线程。

百度到有两种方式在子线程中更新空间,如下

1、使用控件的 Invoke

比如我这里要添加内容到ListBox然后 更新

    public void Notice(string notice)    {        Action<string> action = delegate(string str)        {            if (box != null)            {                box.Items.Add(notice);                box.TopIndex = box.Items.Count - (int)(box.Height / box.ItemHeight);            }        };        box.Invoke(action, new object[] { notice });    }


2、使用SynchronizationContext的Post/Send方法更新

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Threading;namespace WindowsFormsApplication1{    public partial class Form1 : Form    {        SynchronizationContext m_context = null;        Thread m_thread = null;        public Form1()        {            InitializeComponent();            m_context = SynchronizationContext.Current;                    }        private void button1_Click(object sender, EventArgs e)        {            m_thread = new Thread(new ThreadStart(LoopThread));            m_thread.Start();        }        private void LoopThread()        {            m_context.Post(SetLabel, "test");        }        private void SetLabel(object str)        {            label1.Text = str.ToString();        }        private void label1_Click(object sender, EventArgs e)        {        }    }}

然后 让 ListBox 自动定位到最后一个

box.TopIndex = box.Items.Count - (int)(box.Height / box.ItemHeight);



0 0