c# - 通过事件进行线程更新主屏幕

标签 c# multithreading events

我试图获取一个线程来更新GUI,并建议我使用一个事件。

具体来说,应用程序在下面的方法UpdateResult()中给了我一个跨线程错误。
我假设我引发的事件是从线程引发的,因此是问题,因为它试图更新在主线程上运行的GUI。

我做错了什么?

谢谢
达摩

C#代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
public delegate void UpdateScreenEventHandler();
namespace EventHandler
{
    public partial class Form1 : Form
    {

        public static event UpdateScreenEventHandler _UpdateScreen;



        public Form1()
        {
            InitializeComponent();
        }

        public void Form1_Load(object sender, EventArgs e)
        {

            // Add event handlers to Show event.
            _UpdateScreen += new UpdateScreenEventHandler(UpdateResult);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Thread the status check
            Thread trd = new Thread(() => Threadmethod());
            trd.IsBackground = true;
            trd.Start();

        }

        private void Threadmethod()
        {
            // Invoke the event.
            _UpdateScreen.Invoke();
        }

        private void UpdateResult()
        {
            textBox1.Text = "This Is the result";
            MessageBox.Show(textBox1.Text);
        }
    }
}

最佳答案

该事件是从后台线程触发的,因此,如果要从事件处理程序访问UI元素,则需要编码到UI线程。

private void UpdateResult()
{
    textBox1.Invoke(new Action( ()=>
    {
        textBox1.Text = "This Is the result";
        MessageBox.Show(textBox1.Text);
    });
}

另一种选择是在UI线程中触发事件,以便事件处理程序不需要这样做。
private void Threadmethod()
{
    Invoke(new Action(() =>
    {
        // Invoke the event.
        _UpdateScreen.Invoke();
    });
}

关于c# - 通过事件进行线程更新主屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125004/

相关文章:

c# - c#.net 中 throw 和 throw ex 的区别

C# 当父应用程序关闭时关闭子应用程序

c - pthreads:如何断言代码在单线程上下文中运行

java - 在循环中重新创建ExecutorService以进行批处理

events - 我从哪里开始制作 linux 输入法?

c# - 我如何验证日期不是 .net c# 中的 future 日期

java - 当需要对级别进行分组时,C# 中的 EnumSet

multithreading - 每个唯一 id 不超过一个并发线程运行代码的算法

jquery - 如何在原型(prototype)中按类选择事件

javascript - JS : Variable scopes and event-loop