私は非同期処理を学習しており、LongProcess()
はメインスレッドのtextbox1
にアクセスできないとわかります。
C#非同期処理とマルチスレッドエラー
私はボタンbutton1
とテキストボックスtextbox1
を持っています。 LongProcess
に非同期に電話したいと思います。 私のコード:
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)
{
}
}
}
私はボタンをクリックして実行すると、私はエラーを取得:
のSystem.InvalidOperationException:「跨執行緒作業無效:存取控制項 'textBox1テキストボックス' 時所使用
申し訳ありませんが、私のOSの言語は中国語です。
このエラーを修正するにはどうすればよいですか?