C#如何等待返回Task <dynamic>的方法?

Joh*_*ust 7 c# json dynamic task async-await

我有一个方法来解析JSON对象的结果.该方法返回一个Task对象,但是当我运行代码时,我收到以下错误:

'System.Collections.Generic.Dictionary<string,object>' does not contain a definition for 'GetAwaiter'
Run Code Online (Sandbox Code Playgroud)

从动态方法返回的对象是System.Collections.Generic.Dictionary和System.Collections.Generic.KeyValuePair类型的对象数组.这是代码:

private static async Task<dynamic> GetReslutstAsync(string url)
    {
        WebRequest request;
        WebResponse response = null;
        try
        {
            request = WebRequest.Create(url);
            request.Credentials = new NetworkCredential("username", "password", "company");
            //request.Credentials = CredentialCache.DefaultNetworkCredentials;
            response = await request.GetResponseAsync();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            try
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var objects = js.Deserialize<dynamic>(reader.ReadToEnd());
                return objects;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

此处发生异常:

private static async Task<dynamic> MakeRequest(string url)
    {
        try
        {
            return await GetReslutstAsync(url).Result;  //<---- This is where I get the error!
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我相信这与我返回动态类型对象的事实有关.我怎么能绕过这个?我需要在"MakeRequest"方法中等待此任务,以便在请求完成之前它不会继续.

编辑:

我的"MakeRequest"方法是这样的循环:

while (true)
        {
            ClockTimer timer = new ClockTimer();
            timer.StartTimer(); //<---This does not stop untill 5 sec has passed
            MakeRequest("www.someurl.com"); //<--- This just skips into the next loop even if not complete.
        }
Run Code Online (Sandbox Code Playgroud)

我的问题是MakeRequest异步运行,所以基本上,它只是跳过这个并直接进入下一个循环.在请求完成之前,我需要将"MakeRequest"设置为HALT.我已经尝试删除所有async/await关键字,但这只会导致"结果未计算".

n8w*_*wrl 7

这就是你需要的:

return await GetReslutstAsync(url);
Run Code Online (Sandbox Code Playgroud)

你没有等待dynamic,只有返回的任务dynamic.