我正在尝试在我的程序中使用异步和等待的概念。程序突然退出。我试图从几个随机 url 中获取内容长度并对其进行处理并显示每个 url 的字节大小。
代码:
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;
}
}
}
主要
public static void Main(string[] args)
{
asyncclass asyncdemo = new asyncclass();
asyncdemo.MainCall();
}
最佳答案
MainCall
返回未完成的任务,除此之外没有其他代码行,因此您的程序结束
要等待它使用:
asyncdemo.MainCall().Wait();
您需要避免 async void
并将 MainCall
更改为 async Task
以便能够等待来自调用者的它。
因为这似乎是一个控制台应用程序,您不能使用当前版本的 Main
方法使用 await
和 async
编译器(我认为正在讨论 feature,以便在 C# 7 中实现即将到来的实现)。
关于c# - 使用时出现运行时错误和程序退出 - 使用 C# 进行异步和等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885374/