Let's say I have a function
public void SendMessage(Message message)
{
// perform send message action
}
Can I create a delegate for this kind of function? If so, how can I pass a message when I use the delegate?
In my case, the function is used by Thread. Whenever there is an event, I need to send a message to the server, to keep the record. I also need to keep it running in background, so that it won't affect the application. However, the threading needs to use delegate
Thread t = new Thread(new ThreadStart(SendMessage));
and I don't know how to pass the message into the delegate. Thanks.
Sure
public delegate void DelWithSingleParameter(Message m);
Passing a message can be done with the following
DelWithSingleParameter d1 = new DelWithSingleParameter(this.SomeMethod);
d1(new Message());
Also as @Mehrdad pointed out in newer versions of the framework you no longer need to define such delegates. Instead reuse the existing Action<T>
delegate for this type of operation.
Action<Message> d1 = new Action<Message>(this.SomeMethod);
d1(new Message());
sure, just define the delegate that way:
delegate void SendMessageDelegate(Message message);
Then just invoke it as normal:
public void InvokeDelegate(SendMessageDelegate del)
{
del(new Message());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With