Can a delegate carry parameters?

Say I have a function

public void SendMessage(Message message) { // perform send message action } 

Can I create a delegate for this function? If so, how do I pass the message when I use the delegate?

In my case, this function is used by Thread. Whenever there is an event, I need to send a message to the server to save the record. I also need it to run in the background so that it does not affect the application. However, you must use a delegate for streaming

 Thread t = new Thread(new ThreadStart(SendMessage)); 

and I don’t know how to pass the message to the delegate. Thanks.

+4
source share
5 answers
+2
source

Sure,

 public delegate void DelWithSingleParameter(Message m); 

Transmission message can be done as follows

 DelWithSingleParameter d1 = new DelWithSingleParameter(this.SomeMethod); d1(new Message()); 

In addition, as @Mehrdad noted in new versions of the framework, you no longer need to define such delegates. Instead of using the already existing Action<T> delegate for this type of operation.

 Action<Message> d1 = new Action<Message>(this.SomeMethod); d1(new Message()); 
+11
source

of course, just define the delegate as follows:

  delegate void SendMessageDelegate(Message message); 

Then just call it as usual:

  public void InvokeDelegate(SendMessageDelegate del) { del(new Message()); } 
+3
source

Of course, see here for an example.

+1
source

You can also do something like this

 object whatYouNeedToPass = new object(); Thread t = new Thread( () => { // whatYouNeedToPass is still here, you can do what ever you want :) }); t.Start(); 
0
source

All Articles