C#: String as parameter to event?

前端 未结 4 1564
独厮守ぢ
独厮守ぢ 2021-01-04 17:22

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

The form has a richtTextBox. I want the worker-thread to pass strings to the form, so that e

4条回答
  •  借酒劲吻你
    2021-01-04 18:15

    Create your own version of the 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 EventArgs with MyEventArgs and create an MyEventArgs object with your string in it.

    Then you can access it by using the MyEventArgs instance .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;
        });
    }
    

提交回复
热议问题