日期:2014-05-17 浏览次数:20866 次
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); })); }); } } }