现在的位置: 首页 > 综合 > 正文

让多线程 thread 里的值能传回到主界面中,并显示在一个 ListBox 中

2018年04月27日 ⁄ 综合 ⁄ 共 944字 ⁄ 字号 评论关闭

单独的类文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadTest
{
    public class MoreTime
    {
        public delegate void InvokeOtherThead(int i);

        public InvokeOtherThead MainThread;

        public void WaitMoreTime()
        {
            
            for (int i= 0 ; i<20;i++)
            {
                Thread.Sleep(2000);
                
                MainThread(i);
            }
        }
    }
}

启动线程的代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MoreTime mt = new MoreTime();
            mt.MainThread = new MoreTime.InvokeOtherThead(AddToList);

            ThreadStart start = new ThreadStart(mt.WaitMoreTime);
            Thread thread = new Thread(start);
            thread.Start();
        }

        public void AddToList(int i)
        {
            if (this.listBox1.InvokeRequired)
            {
                MoreTime mt = new MoreTime();
                mt.MainThread = new MoreTime.InvokeOtherThead(AddToList);

                this.Invoke(mt.MainThread, new object[] { i});

            }
            else
            {
                listBox1.Items.Add(i.ToString());
            }
        }
    }
}
【上篇】
【下篇】

抱歉!评论已关闭.