日期:2014-05-17  浏览次数:20866 次

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