开发者

Can a delegate carry parameters?

开发者 https://www.devze.com 2022-12-17 06:06 出处:网络
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 us

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开发者_Python百科. 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());
 }


You need to use a ParametizedThreadStart. See here:

http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx


Sure, see here for an example.


You can also do thing like that

object whatYouNeedToPass = new object();

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

t.Start();
0

精彩评论

暂无评论...
验证码 换一张
取 消