首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

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

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);                        }));                    });                }            }        } 

热点排行