我试图获取一个线程来更新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/