C#C
C#2y ago
VerpinZal

Auto-translation, HttpClient, Result, await...

This is my code inside an application for translation purposes. It queries the user's OS for the installed language, retrieves the two letter ISO language code, sends it to google along with strings and displays the translated text. However, only in debug mode, this code sometimes throws an access violation reading location exception at "var result" line. I know why that is, because Result is running async and it's blocking the thread until Result is retrieved. Solution appears to be converting the entire method to async Task<string>. Problem is, I racked my brains to find a way to convert Task<string> to string, to no avail. I've been tinkering with just this method intermittently for two weeks now and I'm at my wit's end. Could a kind soul at least provide me with some hints or point to the right direction? I change the code as var result = await HttpClient.GetStringAsync(url); and the code builds. How do I proceed then? What's the right method to call this function so it displays the right strings instead of System.Task.Task`f or the like? Thanks a million.

public string TranslateText(string input, string twoLetterIsolanguageCode)
{

    if (CheckForInternetConnection())
    {
        string url = String.Format
        ("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
        "en",
        twoLetterIsolanguageCode,
        Uri.EscapeUriString(input));

        HttpClient httpClient = new HttpClient();
        var result = httpClient.GetStringAsync(url).Result;

        var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result);

        var translationItems = jsonData[0];

        string translation = "";

        foreach (object item in translationItems)
        {
            IEnumerable? translationLineObject = item as IEnumerable;

            IEnumerator translationLineString = translationLineObject.GetEnumerator();

            translationLineString.MoveNext();

            translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
        }

        if (translation.Length > 1) { translation = translation.Substring(1); };

        return translation;

    }
    else
    {
        return input;
    }


}
Was this page helpful?