C#异步处理和多线程错误

C#异步处理和多线程错误,c#,multithreading,asynchronous,runtime-error,C#,Multithreading,Asynchronous,Runtime Error,我正在学习异步处理,发现LongProcess()无法访问主线程的textbox1 我有一个按钮button1和一个文本框textbox1。 我想异步调用LongProcess。 我的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text

我正在学习异步处理,发现
LongProcess()
无法访问主线程的
textbox1

我有一个按钮
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.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用系统线程;
使用System.Windows.Forms;
命名空间异步
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
}
公共流程()
{
对于(int i=0;i<1500;i++)
{
textBox1.Text+=“/----/”+i;
}
如果(textBox1.Text!=“”)
{
textBox1.Text+=“//”;
}
}
公共任务调用过程()
{
返回任务。运行(()=>
{
长流程();
});
}
私有异步无效按钮1\u单击(对象发送方,事件参数e)
{
等待CallProcess();
}
私有void textBox1\u TextChanged(对象发送方,事件参数e)
{
}
}
}
当我运行时,单击按钮,我得到一个错误:

System.InvalidOperationException:'跨執行緒作業無效: 存取控制項 '文本框1'時所使用的執行緒與建立控制項的執行緒不同。'

对不起,我的操作系统的语言是中文


如何修复此错误?

必须使用UI线程更新UI。由于您正在更新UI元素(即
textBox1
),因此需要使用适当的线程。在WPF中,这可以通过类或WinForms通过类中的
Invoke
BeginInvoke
函数来完成。我强烈建议您熟悉和