chahid khalil
chahid khalil

Reputation: 19

Call webservice asynchronously

I need to call a web service so I added the webservice as web reference and I am able to call it. Now I need to make that call async because it need to download lot of data and it is taking lot of time. I tried to use the async/await method but I can not do this since the method in the webservice are not async.

Original code:

 public static void validateLogin(JsonParameters _param, ref ValidateCredentials result, ref string excep_error)
    {
        var _mobileService = new MobileService();
        _mobileService.Url = AppParam.IISSTRING + "/UrlAddressReference";
        try
        {
            result = _mobileService.downloaddata(_param);
        }
        catch (Exception ex)
        {
            excep_error = ex.Message;
        }

    }

I tried to add async task in place of void to make the method async, but how can I await the webservice response?

After I added the webservice as a web reference I can see that it created for each method in it an async method and completed event. How can I make use of them? (Ex: downloaddata", a method namedownloaddataasync`, and an event "downloaddatacompleted")

Is there a way to do this or do I need to change the webservice?

Upvotes: 0

Views: 127

Answers (3)

Stephen Cleary
Stephen Cleary

Reputation: 456437

After I added the webservice as a web reference I can see that it created for each method in it an async method and completed event. How can I make use of them?

Those are EAP members. You need to write TAP wrappers for those EAP members; then you can use async/await like normal.

Upvotes: 1

Yuri S
Yuri S

Reputation: 5370

public async static Task validateLogin(JsonParameters _param, ref ValidateCredentials result, ref string excep_error)
        {
          await Task.Run(()=>
          {
            var _mobileService = new MobileService();
            _mobileService.Url = AppParam.IISSTRING + "/UrlAddressReference";
            try
            {
                result = _mobileService.downloaddata(_param);
            }
            catch (Exception ex)
            {
                excep_error = ex.Message;
            }
         });
}

Upvotes: 0

Jared Dykstra
Jared Dykstra

Reputation: 3626

If you want to use async/await, the correct approach is as you suggested: change the validateLogin to public static async Task validateLoginAsync(...) The method that calls validateLogin needs to be changed, and the one calling it, etc.

It may be possible for you to use AsyncContext or NotifyTaskCompletion as a crutch (from https://github.com/StephenCleary/AsyncEx/wiki/AsyncContext) but you still may need to use a BackgroundWorker or similar construct as well.

Upvotes: 0

Related Questions