using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApp54
{
public partial class Form1 : Form
{
Task task;//定义Task类型字段
int myValue = 0;//初始化myValue,最终在工作线程中把Value传递到Form窗体中的Text文本中。
public Form1()
{
InitializeComponent();
task = new Task(MyThreadMethod);
}
private void button1_Click(object sender, EventArgs e)
{
task.Start();//启动MyThreadMethod方法(工作线程)
}
private void MyThreadMethod()
{
while (true)
{
myValue++;
textBox1.Invoke(new Action(UpdateTextBox));//调用UpdateTextBox方法。
Thread.Sleep(1000);
}
}
private void UpdateTextBox()
{
textBox1.Text = myValue.ToString();
}
}
}