等待异步澄清 [英] Await async clarification

查看:124
本文介绍了等待异步澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习/了解更多关于异步/等待在C#和我把自己在新秀类别,这样所有的意见/建议都欢迎。我写了小试,以有更好的理解和澄清等待/异步。我的程序冻结后GetStringLength叫我尝试读几件事情,但看起来像我坚持,我想采取什么我可能是做错了专家的意见。能否请您指导我或点我在这里朝着正确的方向?

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Net;
使用System.Text;
使用的System.Threading;
使用System.Threading.Tasks;命名空间AsyncPatterns
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            程序P =新计划();
            任务<串GT; URL = p.FindLargtestWebPage(新的URI [] {新的URI(http://www.google.com),
                                                            新的URI(http://www.facebook.com),
                                                            新的URI(http://www.bing.com)});
            Console.WriteLine(url.Result);
            到Console.ReadLine();
        }        公共异步任务<串GT; FindLargtestWebPage(URI []的URI)
        {
            字符串highCountUrl =的String.Empty;
            INT MAXCOUNT = 0;            的foreach(在乌里的URI URI)
            {
                Console.WriteLine(的String.Format(处理{0},uri.ToString()));
                VAR pageContent =等待GetWebPageString(URI);
                变种数=等待GetStringLength(pageContent);
                如果(计数> MAXCOUNT)
                {
                    highCountUrl = uri.ToString();
                }
            }
            返回highCountUrl;
        }        公共异步任务< INT> GetStringLength(字符串pageData)
        {
            Console.WriteLine(获得长);
            返回等待新的任务<&诠释GT;(()=>
            {
                返回pageData.Length;
            });
        }        公共异步任务<串GT; GetWebPageString(URI URI)
        {
            Web客户端Web客户端=新的WebClient();
            Console.WriteLine(下载字符串);
            返回等待webClient.DownloadStringTaskAsync(uri.ToString());
        }    }
}


解决方案

冻结罪魁祸首是这样的:

 返回等待新的任务< INT>(()=>
{
    返回pageData.Length;
});

工作构造函数不启动任务,所以您要创建一个工作不是运行。当你等待上的 GetStringLength 你要的结果永远等待。

您可以手动启动任务:

  VAR的结果=新的任务< INT>(()=>
{
    返回pageData.Length;
});result.Start();返回结果;

Task.Run 静态方法,这将创建并启动任务:

 返回Task.Run(()=>
{
    返回pageData.Length;
});

I am trying to learn/understand more about async/await in C# and I would put myself in rookie category so all your comments/suggestions are welcome. I wrote small test to have better understanding and clarification about await/async. My program freezes after "GetStringLength" call I tried reading several things but looks like I am stuck and I thought of taking expert opinion on what I might be doing wrong. Can you please guide me or point me in right direction here?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncPatterns
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Task<string> url = p.FindLargtestWebPage(new Uri[]{new Uri("http://www.google.com"), 
                                                            new Uri("http://www.facebook.com"), 
                                                            new Uri("http://www.bing.com") });
            Console.WriteLine(url.Result);
            Console.ReadLine();
        }

        public async Task<string> FindLargtestWebPage(Uri[] uris)
        {
            string highCountUrl = string.Empty;
            int maxCount = 0;

            foreach (Uri uri in uris)
            {
                Console.WriteLine(string.Format("Processing {0}", uri.ToString()));
                var pageContent = await GetWebPageString(uri);
                var count = await GetStringLength(pageContent);
                if (count > maxCount)
                {
                    highCountUrl = uri.ToString();
                }
            }
            return highCountUrl;            
        }

        public async Task<int> GetStringLength(string pageData)
        {
            Console.WriteLine("Getting length");
            return await new Task<int>(() =>
            {
                return pageData.Length;
            });
        }

        public async Task<string> GetWebPageString(Uri uri)
        {
            WebClient webClient = new WebClient();
            Console.WriteLine("Downloading string");
            return await webClient.DownloadStringTaskAsync(uri.ToString());
        }

    }
}

解决方案

The culprit for freezing is this:

return await new Task<int>(() =>
{
    return pageData.Length;
});

This Task constructor doesn't start the task, so you're creating a Task that isn't running. When you await on it in GetStringLength you're going to be waiting forever for the result.

You can either start the task manually:

var result = new Task<int>(() =>
{
    return pageData.Length;
});

result.Start();

return result;

or use the Task.Run static method, which will create and start the task:

return Task.Run(() =>
{
    return pageData.Length;
});

这篇关于等待异步澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆