In other recent work, using winform project development is sometimes necessary to control the use of other threads created when multiple threads in parallel, or is required to use some of the information (the contents of a text box, button clicks, etc.) in the form of other, more use of delegates and events , so I wrote a simple example record it.
To use delegates, first of all I must declare
// declare a delegate Private the delegate void TestDelegate ( String the addText, the RichTextBox TEMP); // delegate variable Private TestDelegate Test { GET ; SET ;}
Because it is used in multi-threaded, so write a method call delegate delegate's statement in the thread
// call the delegate Private void InvokeDelegate ( String addText, the RichTextBox the TEMP) { if (temp != null && temp.InvokeRequired) { temp.BeginInvoke(this.test, new object[] { addText, temp }); } }
Commissioned variable instantiation in another thread and delegate invocation
test = new TestDelegate(AddText); InvokeDelegate(_addText, _tempRichTextBox); private void AddText(string addText, RichTextBox temp) { temp.Text += addText + "\r\n"; }
The above is a simple example of the use of multiple threads commission to control the use of
And then look at an event for messaging between controls
At the outset delegates and events
// delegate public delegate void DelegateTest ( String text); // Events public Event DelegateTest AddTextEvent;
Carried out (release event) Invoke the desired position for messaging
AddTextEvent?.Invoke(text);
In the call events (event subscription)
EventTest et = new EventTest(); et.AddTextEvent + = new EventTest.DelegateTest (Et_AddTextEvent); private void Et_AddTextEvent(string text) { this.testRichTextBox.Text += text + "\r\n"; }
C # event is mainly used for messaging (communication) between threads, using a publish - subscribe model. Event Event declared in the class, the class that contains the event to publish the event, called the Publisher , Publisher class ; receiving other classes of the event is to subscribe to the event, called up for Subscriber , the subscription class .
These are examples of using delegates and events in winform to communicate between threads.
Full version of the code on GitHub: https://github.com/hhhhhaleyLi/DelegateTest