i am learning async processing , and i find LongProcess()
can't access the textbox1
of the main thread .
I have a button button1
and a textbox textbox1
.
I want to call LongProcess
asynchronously.
my code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
namespace Async
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void LongProcess()
{
for (int i = 0; i < 1500; i++)
{
textBox1.Text += "/-------/" + i;
}
if (textBox1.Text != "")
{
textBox1.Text += "/////////////";
}
}
public Task CallProcess()
{
return Task.Run(() =>
{
LongProcess();
});
}
private async void button1_Click(object sender, EventArgs e)
{
await CallProcess();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
When i run click the button , i get an error :
System.InvalidOperationException: '跨執行緒作業無效: 存取控制項 'textBox1' 時所使用的執行緒與建立控制項的執行緒不同。'
Sorry , the language of my OS is chinese .
How can i fix this error ?