Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Gcm Network Manager await httpclient

I'm using the Gcm Network Manager to schedule tasks, in one of those tasks I need to perform an HTTP request. Until now it was written with HttpWebRequest so nothing was async.

Now I would like to reuse code that is written with HttpClient and is async.

The problem that arrises is that I cannot make the OnRunTask() async as it needs to return an int:

e.g.

public override int OnRunTask(TaskParams @params)
{
    var result = await performSync();

    if(result)
    {
        return GcmNetworkManager.ResultSuccess;
    }

    return GcmNetworkManager.ResultReschedule;
}

What could I do to be able to reuse async code here ?

like image 646
RVandersteen Avatar asked Nov 19 '25 12:11

RVandersteen


1 Answers

You can use Task.Run inside your OnRunTask method like this :

 Task.Run( async () =>
        {
             // Do your stuff here
             await asyncTask();
        });

You will no need to have OnRunTask async with this technique

Hope it helps

Edit

If you need the return value to match the framework / library signature, you can also use .Result

E.g.

var result = asyncTask().Result;
...
like image 168
fandro Avatar answered Nov 21 '25 05:11

fandro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!