0

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 ?

Ben
  • 39
  • 1
  • 10

1 Answers1

0

The UI must be updated using the UI thread. Since you are updating a UI element (i.e. textBox1), you need to use the appropriate thread. In WPF this can be done via the Dispatcher class or in WinForms via the Invoke or BeginInvoke functions from the Control class. I highly recommend getting acquainted with the Async/Await model and best practices.

linuxuser27
  • 7,183
  • 1
  • 26
  • 22