The new Task class works great in WPF. However in Winforms, it is always stuck every time it tries to access a Winform control. The "InvokeRequired" routine below that has been working with BackgroundWorker and Thread classes that prevents cross-thread operation error. However, for some reason when it comes to Task, it gets stuck on the Invoke method. Help ?
Here is a sample code. I use NET 4.5.1 framework.
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinformTaskDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string now = DateTime.Now.ToString();
Task t = new Task(() => { setText(now); });
t.Start();
t.Wait();
}
private void setText(string text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new Action(() => textBox1.Text = text)); //stuck forever here
}
else
{
textBox1.Text = text;
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire