C#:字符串作为事件的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12055431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:13:59  来源:igfitidea点击:

C#: String as parameter to event?

c#.netmultithreadingeventsevent-handling

提问by think

I have a GUI-thread for my form and another thread that computes things.

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

The form has a richtTextBox. I want the worker-thread to pass strings to the form, so that every string is displayed in the textbox.

该表单有一个richtTextBox。我希望工作线程将字符串传递给表单,以便每个字符串都显示在文本框中。

Everytime a new string is generated in the worker thread I call an event, and this should now display the string. But I don't know how to pass the string! This is what I tried so far:

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

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


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

采纳答案by Jodrell

Like this

像这样

public class NewListEntryEventArgs : EventArgs
{
    private readonly string test;

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

    public string Test
    {
        get { return this.test; }
    }
}

then you declare your class like this

然后你像这样声明你的类

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

and in the subscribing Form

并在订阅中 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;
}


I've taken the liberty of making the NewListEntryEventArgsclass immutable, since that makes sense. I've also partially corrected your naming conventions, simplified and corrected where expedient.

我冒昧地使NewListEntryEventArgs类不可变,因为这是有道理的。我还部分更正了您的命名约定,在方便的地方进行了简化和更正。

回答by Martin Milan

You need to create a new class by inheriting off EventArgs.

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

回答by Amiram Korach

In general you need to inherit EventArgsand add a stringproperty, and then make your event of type EventHandler<YourEventArgs>, but that is a classic case for the BackgroundWorker.

一般来说,您需要继承EventArgs并添加一个string属性,然后使您的事件类型为EventHandler<YourEventArgs>,但这是BackgroundWorker.

Sample here: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

此处示例:http: //msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

and here: C# backgroundWorker reports string?

在这里: C# backgroundWorker 报告字符串?

回答by Gerald Versluis

Create your own version of the EventArgs.

创建您自己的EventArgs.

Do it like this:

像这样做:

public class MyEventArgs : EventArgs
{
   public string MyEventString {get; set; }

   public MyEventArgs(string myString)
   {
       this.MyEventString = myString;
   }
}

Then in your code replace the EventArgswith MyEventArgsand create an MyEventArgsobject with your string in it.

然后在您的代码中替换EventArgswithMyEventArgs并创建一个MyEventArgs包含您的字符串的对象。

Then you can access it by using the MyEventArgsinstance .MyEventString.

然后您可以使用MyEventArgs实例访问它.MyEventString

So you would do something like this:

所以你会做这样的事情:

///// myClass (working thread...)
class myClass
{
    public event EventHandler NewListEntry;

    public void ThreadMethod()
    {
        DoSomething();
    }

    protected virtual void OnNewListEntry(MyEventArgs 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";

        OnNewListEntry(new MyEventArgs(test));
    }
}

And in your form:

并以您的形式:

private void myObj_NewListEntry(Object objSender, MyEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate
    {
        // Here I want to add my string from the worker-thread to the textbox!
        richTextBox1.Text += e.MyEventString;
    });
}