Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

c# - How do I access variables from a different thread?

Getting error: Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.

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 WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        string CONNECTING = "Connecting to server...";
        string GETTING_DATA = "Getting data...";
        string CONNECT_FAIL = "Failed to connect!";
        string CONNECT_SUCCESS = "Connection established!";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread t1 = new Thread(run);
            t1.Start();
        }

        public void run() {
            label1.Text = CONNECTING;
        }
    }
}

How do I properly fix this? I've tried using CheckForIllegalCrossThreadCalls = false; but that obviously causes errors.

I'd also like to know how I can stop the thread, since it can't be accessed anymore outside of that function.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using BeginInvoke:

public void run() 
{
    label1.BeginInvoke(new Action(() =>
    {
        label1.Text = CONNECTING;
    }));
}

Only the UI thread can update UI elements in a Windows Forms app. Other threads need to use BeginInvoke to update the UI.

ORGINAL: i assumed this was a WPF app and said to use this.Dispatcher, but Dispatcher isn't in Windows Forms apps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...