1

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);
        }
    }
}
4

2 に答える 2

3

イベントはバックグラウンドスレッドから発生するため、イベントハンドラーからUI要素にアクセスする場合は、UIスレッドにマーシャリングする必要があります。

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

もう1つのオプションは、UIスレッドでイベントを発生させて、イベントハンドラーがそれを実行する必要がないようにすることです。

private void Threadmethod()
{
    Invoke(new Action(() =>
    {
        // Invoke the event.
        _UpdateScreen.Invoke();
    });
}
于 2013-01-02T15:57:31.577 に答える
0

同じスレッドでテキストボックスを設定します。あなたのイベントからこれを呼び出します。

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.Text = text;
        }
    }

これは、次のMSDNリンクによるものです。

http://msdn.microsoft.com/en-us/library/ms171728%28v=vs.80%29.aspx

于 2013-01-02T15:58:40.047 に答える