简体   繁体   中英

Getting instance of delegate from inside itself C#

I am working with a WCF service, calls to the service are invoked using an async method. As I am working with Xamarin studio the WCF proxy must be created using the silverlight tools (slsvcutil.exe) and as such this seems to be the only way to achieve what I am doing.

To make a call to the service I must make a call like so:

Soap.client.DoActionCompleted += Soap_client_DoActionCompleted;
Soap.client.DoActionAsync(parameter);

And then declare the delegate for DoActionCompleted like so:

void Soap_client_DoActionCompleted(object sender, DoActionCompletedEventArgs e)
{
    Soap.client.DoActionCompleted -= Soap_client_DoActionCompleted;
    // Do stuff
}

I have to remove Soap_client_DoActionCompleted after the call to prevent it from stacking further calls on it later.

The problem is I have many calls like this in my code, and it is beginning to get very messy and hard to follow the logic when writing the code. I would much prefer to be able to declare the code inline so it's much easier to follow, something like this:

Soap.client.DoActionCompleted += (sender, e) =>
{
    Soap.client.DoActionCompleted -= x;
    // Do stuff
}

Soap.client.DoActionAsync(parameter);

In the above snippet, I'd like to be able to pass the delegate that it is inside to remove it then and there, but the problem is I have no idea if this is even possible.

While I know there are almost certainly better ways of doing the above, I'm a little trapped by the fact that I am required to use slsvcutil.exe to generate the proxy for the service, and writing the proxy manually isn't an option as the service gets regular updates.

It's kind of possible if you assign the lambda expression to a delegate variable first. It just won't be as nice as what you're hoping for.

And even then, to avoid a use of unassigned local variable compiler error, you have to first initialize the delegate variable to null before you can assign the lambda expression that will have a reference to itself.

So, using your example, it would look like this (I'm assuming the type of DoActionCompleted is EventHandler . Simply adjust if I'm wrong):

EventHandler eventHandler = null;
eventHandler = (sender, e) => 
{
    Soap.client.DoActionCompleted -= eventHandler;
    // do stuff
};
Soap.client.DoActionCompleted += eventHandler;

Soap.client.DoActionAsync(parameter);

It's up to you to decide if it's worth it for you to use this pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM