Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Cannot await on Task<string>' (PCL Xamarin Studio)

I'm trying to write the following method:

    public async Task<string> GetJson(string url, 
                    Dictionary<string,string> parameters = null){

        // parameters?
        if (parameters != null) {
            if (parameters.Count > 0) {
                url += "?";
                foreach(var key in parameters.Keys){

                    // add parameter to url
                    url += String.Format("{0}={1}", key, parameters[key]);

                    // more parameters?
                    if(!parameters.Keys.Last ().Equals(key)){
                        url += "&";
                    }
                }
            }
        }
        // send request
        var uri = new Uri(url);
        var req = new HttpClient();
        Task<string> getJsonTask = req.GetStringAsync(uri);
        // EXCEPTION : 'Cannot await on Task<string>'
        return await getJsonTask;
    }

I get an error at compilation time. I don't think the problem is the syntax. I think is a dependencies issue. My references are:

enter image description here

I added them using Nuget. Any ideas about what could be the issue?

Thanks in advance.

UPDATE

Suggested by Selman22:

    public async Task<string> GetJson(string url, Dictionary<string,string> parameters = null){
        // ...
        return await req.GetStringAsync(uri); // Same exception
    }

Suggested by Kenneth:

    public Task<string> GetJson(string url, Dictionary<string,string> parameters = null){
        // ...
        return req.GetStringAsync(uri); // no problems here
    }

    // Later when trying to invoke GetJson
    public async Task<List<Station>> GetStations(){
        var url = String.Format(
            "?{0}_id{1}&_render=json", 
            DublinBikeDataProvider.BASE_URL,
            DublinBikeDataProvider.STATIONS
        );
        var json = await this._httpClient.GetJson(url); // same exception
        return this.ParseStations(json);
    }
like image 400
Remo H. Jansen Avatar asked Feb 02 '14 21:02

Remo H. Jansen


1 Answers

Ensure that you have installed the Microsoft.Bcl.Async NuGet library. If you change your PCL target platforms, you should uninstall all NuGet packages and re-install them.

like image 173
Stephen Cleary Avatar answered Sep 24 '22 14:09

Stephen Cleary