using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task[] a = new Task[12];
for (int i = 0; i < 12; i++)
{
a[i] = new Task(MGo, i.ToString());
a[i].Start();
}
//Task.WaitAll(a);
//MessageBox.Show("OK");
}
private void MGo(object obj)
{
while (true)
{
CrossThreadCalls.SafeInvoke(this.label1, new CrossThreadCalls.TaskDelegate(delegate()
{
listBox1.Items.Add(DateTime.Now.Ticks.ToString());
}));
Thread.Sleep(1000);
}
}
}
public static class CrossThreadCalls
{
public delegate void TaskDelegate();
private delegate void InvokeMethodDelegate(Control control, TaskDelegate handler);
//CrossThreadCalls.SafeInvoke(this.label1, new CrossThreadCalls.TaskDelegate(delegate()
//{
// listBox1.Items.Add(DateTime.Now.Ticks.ToString());
//}));
public static void SafeInvoke(Control control, TaskDelegate handler)
{
if (control.InvokeRequired)
{
while (!control.IsHandleCreated)
{
if (control.Disposing || control.IsDisposed)
return;
}
IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
control.EndInvoke(result);
return;
}
IAsyncResult result2 = control.BeginInvoke(handler);
control.EndInvoke(result2);
}
}
}
根据http://www.cnblogs.com/slyzly/articles/2121436.html 此人的代码写的,但是发现只要执行了Task.WaitAll(a);程序就一直卡死在那里不显示输出了,why? 怎么改?
------解决思路----------------------
所谓的"显示出来",需要代码执行对不?
而一旦WaitAll了,UI线程就停在那里了,哪来的线程去执行“显示出来”?