The instruction
Func<int> del = delegate ()
{
txttcpResultados.AppendText(s + Environment.NewLine);
return 0;
};
What it does is declare a variable del
whose value is a function that does not receive any parameter and returns an integer value.
This can be useful in many cases, mainly when you want to pass a method or function as an argument to another method. Typical cases of using delegates can be controllers of control events in Windows Forms or a sort function that is passed to a method in a list.
In the list handling methods you can find many examples ( Enumerable. OrderBy )
The instruction
Invoke(del);
What you are doing is calling the method Invoke
of the object on which the method is executed, for the code I guess it will be a Form
of Windows Forms.
What the Invoke
method does is to execute the del
delegate in the same thread in which the window in which the control is contained is running. This can be very practical in multi-threaded scenarios, in which the code may be running on a different thread but the interface update instructions must be executed on the same thread as the window.
Regarding the last question. If the delegate had an argument of type string
you should pass it to the method Invoke
. Otherwise, you will receive an exception of System.Reflection.TargetParameterCountException
.
The call should be:
Invoke(del, micadena);