C#:String作为事件的参数?

thi*_*ink 9 .net c# events multithreading event-handling

我有一个用于表单的GUI线程和另一个计算事物的线程.

表单有一个richtTextBox.我希望worker-thread将字符串传递给表单,以便每个字符串都显示在文本框中.

每次在工作线程中生成一个新字符串时,我都会调用一个事件,现在应该显示该字符串.但我不知道如何传递字符串!这是我到目前为止所尝试的:

///// Form1
private void btn_myClass_Click(object sender, EventArgs e)
{
    myClass myObj = new myClass();
    myObj.NewListEntry += myObj_NewListEntry;
    Thread thrmyClass = new Thread(new ThreadStart(myObj.ThreadMethod));
    thrmyClass.Start();
}

private void myObj_NewListEntry(Object objSender, EventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate
    {
        // Here I want to add my string from the worker-thread to the textbox!
        richTextBox1.Text += "TEXT"; // I want: richTextBox1.Text += myStringFromWorkerThread;
    });
}
Run Code Online (Sandbox Code Playgroud)
///// myClass (working thread...)
class myClass
{
    public event EventHandler NewListEntry;

    public void ThreadMethod()
    {
        DoSomething();
    }

    protected virtual void OnNewListEntry(EventArgs e)
    {
        EventHandler newListEntry = NewListEntry;
        if (newListEntry != null)
        {
            newListEntry(this, e);
        }
    }

    private void DoSomething()
    {
        ///// Do some things and generate strings, such as "test"...
        string test = "test";


        // Here I want to pass the "test"-string! But how to do that??
        OnNewListEntry(EventArgs.Empty); // I want: OnNewListEntry(test);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jod*_*ell 21

像这样

public class NewListEntryEventArgs : EventArgs
{
    private readonly string test;

    public NewListEntryEventArgs(string test)
    {
        this.test = test;
    }

    public string Test
    {
        get { return this.test; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就像这样申报你的班级

class MyClass
{
    public delegate void NewListEntryEventHandler(
        object sender,
        NewListEntryEventArgs args);

    public event NewListEntryEventHandler NewListEntry;

    protected virtual void OnNewListEntry(string test)
    {
        if (NewListEntry != null)
        {
            NewListEntry(this, new NewListEntryEventArgs(test));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在订阅 Form

private void btn_myClass_Click(object sender, EventArgs e)
{
    MyClass myClass = new MyClass();
    myClass.NewListEntry += NewListEntryEventHandler;
    ...
}

private void NewListEntryEventHandler(
    object sender,
    NewListEntryEventArgs e)
{
    if (richTextBox1.InvokeRequired)
    {
        this.Invoke((MethodInvoker)delegate
            {             
                this.NewListEntryEventHandler(sender, e);
            });
        return;
    }

    richTextBox1.Text += e.Test;
}
Run Code Online (Sandbox Code Playgroud)

我冒昧地让这个NewListEntryEventArgs类不可变,因为这是有道理的.我还部分更正了您的命名约定,简化并更正了权宜之计.


Mar*_*lan 5

您需要通过继承 EventArgs 来创建一个新类。