简体   繁体   English

运行时错误和程序退出时使用 - 异步和等待使用C#

[英]Run time error and Program exits when using - Async and await using C#

I am trying to use the concept of async and await in my program. 我试图在我的程序中使用async的概念并等待。 The program abruptly exits. 该程序突然退出。 I am trying to get the content length from few random urls and process it and display the size in bytes of each url. 我试图从几个随机网址获取内容长度并处理它并显示每个网址的字节大小。

Code: 码:

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

namespace TestProgram
{
    public class asyncclass
    {

        public async void  MainCall() {

             await SumPageSizes();

        }

        public async Task SumPageSizes(){

            List<string> urllist = GetUrlList();

            foreach (var url in urllist)
            {
                byte[] content = await GetContent(url);
                Displayurl(content, url);

            }


        }

        private void Displayurl(byte[] content, string url)
        {
            var length = content.Length;
            Console.WriteLine("The bytes length for the url response " + url + " is of :" +length );
        }

        private async Task<byte[]> GetContent(string url)
        {
            var content = new MemoryStream();

            try
            {


                var obj = (HttpWebRequest)WebRequest.Create(url);

                WebResponse response = obj.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    await stream.CopyToAsync(content);

                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);

            }

            return content.ToArray();
        }

        private List<string> GetUrlList()
        {
            var urllist = new List<string>(){
                "http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
                "http://msdn.microsoft.com",
                "http://msdn.microsoft.com/en-us/library/hh290136.aspx",
                "http://msdn.microsoft.com/en-us/library/ee256749.aspx",
                "http://msdn.microsoft.com/en-us/library/hh290138.aspx",
                "http://msdn.microsoft.com/en-us/library/hh290140.aspx",
                "http://msdn.microsoft.com/en-us/library/dd470362.aspx",
                "http://msdn.microsoft.com/en-us/library/aa578028.aspx",
                "http://msdn.microsoft.com/en-us/library/ms404677.aspx",
                "http://msdn.microsoft.com/en-us/library/ff730837.aspx"
            };
            return urllist;
        }
    }
}

Main 主要

 public static void Main(string[] args)
        {
            asyncclass asyncdemo = new asyncclass();
            asyncdemo.MainCall();

        }

MainCall returns an uncompleted task and no other line of code is present beyond that, so your program ends MainCall返回一个未完成的任务, MainCall没有其他代码行,因此您的程序结束

To wait for it use: 等待它使用:

asyncdemo.MainCall().Wait();

You need to avoid async void and change MainCall to async Task in order to be able to wait for it from the caller. 您需要避免async void并将MainCall更改为async Task ,以便能够从调用者等待它。

Since this seems to be a console application, you can't use the await and async for the Main method using the current version of the compiler (I think the feature is being discussed for upcoming implementation in C# 7). 由于这似乎是一个控制台应用程序,因此您无法使用当前版本的编译器对Main方法使用awaitasync (我认为该功能正在讨论即将在C#7中实现)。

The problem is that you don't await an asynchron method and therefore you application exits before the method ended. 问题是您没有等待异步方法,因此应用程序在方法结束之前退出。

In c# 7 you could create an async entry point which lets you use the await keyword. 在c#7中,您可以创建一个异步入口点 ,允许您使用await关键字。

public static async Task Main(string[] args)
{
    asyncclass asyncdemo = new asyncclass();
    await asyncdemo.MainCall();
}

If you want to bubble your exceptions from MainCall you need to change the return type to Task . 如果要从MainCall异常, MainCall需要将返回类型更改为“ Task

public async Task MainCall() 
{
    await SumPageSizes();
}

If you wanted to run your code async before c# 7 you could do the following. 如果您想在c#7之前运行代码异步,则可以执行以下操作。

public static void Main(string[] args)
{
    asyncclass asyncdemo = new asyncclass();
    asyncdemo.MainCall().Wait();
    // or the following line if `MainCall` doesn't return a `Task`
    //Task.Run(() => MainCall()).Wait();
}

You have to be very careful when using async void methods. 使用异步void方法时必须非常小心。 Those will not be awaited. 那些将不会被等待。 One normal example of an async void is when you are calling an awaitable method inside a button click: 异步void的一个常见示例是当您在按钮单击内调用等待方法时:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    // run task here
}

This way the UI won't be stuck waiting for the button click to complete. 这样UI就不会等待按钮点击完成。 On most custom methods you will almost always want to return a Task so that you are able to know when your method is finished. 在大多数自定义方法中,您几乎总是希望返回一个Task,以便您能够知道方法何时完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM