读书人

c# 多线程实施一个带参方法

发布时间: 2012-09-20 09:36:50 作者: rapoo

c# 多线程执行一个带参方法
问题描述,我有一个ping类,中一个ping方法,如何根据设置的线程数,来执行方法?

[解决办法]
大概是这样

C# code
        public static Random R = new Random();        public static string Ping(object arg)        {            var span = R.Next(1000);            Thread.Sleep(span);            return arg + " " + span.ToString();        }        private void button1_Click(object sender, EventArgs e)        {            int threadNum = 10;            int totalNum = 100;            Task[] tasks = new Task[10];            for (int i = 0; i < totalNum; i++) {                int idx = i % threadNum;                if (tasks[idx] == null) {                    Task t = new Task(() => {                        var ret = Ping("somthing");                        this.Invoke(new Action(() => {                            this.listBox1.Items.Add(ret);                            this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);                        }));                    });                    tasks[idx] = t;                    t.Start();                } else {                    tasks[idx] = tasks[idx].ContinueWith(t => {                        var ret = Ping("somthing");                        this.Invoke(new Action(() => {                            this.listBox1.Items.Add(ret);                            this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);                        }));                    });                }            }        } 

读书人网 >C#

热点推荐