c# – 在Mono上简单的HttpClient测试失败
发布时间:2020-12-16 01:56:38 所属栏目:百科 来源:网络整理
导读:在Mac OS X上对Mono(3.2.1)执行这个简单的小测试时,它从不打印任何对控制台的响应,而是说关闭终结器线程超时. 这段代码有问题还是我的Mono行为不端? using System;using System.Net.Http;namespace VendTest{ class MainClass { public static void Main(st
在Mac OS X上对Mono(3.2.1)执行这个简单的小测试时,它从不打印任何对控制台的响应,而是说关闭终结器线程超时.
这段代码有问题还是我的Mono行为不端? using System; using System.Net.Http; namespace VendTest { class MainClass { public static void Main(string[] args) { Client client = new Client(); client.HttpClientCall(); } } public class Client { HttpClient client; public Client() { client = new HttpClient(); } public async void HttpClientCall() { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync("http://vendhq.com"); string responseAsString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseAsString); } } } 解决方法
你几乎不应该使用异步void方法,这就是原因之一.你的Main()将在HttpClientCall()实际完成之前结束.由于退出Main()会终止整个应用程序,因此不会打印任何内容.
你应该做的是在Main()中将你的方法改为异步Task和Wait(). (混合await和Wait()通常会导致死锁,但它是控制台应用程序的正确解决方案.) class MainClass { public static void Main() { new Client().HttpClientCallAsync().Wait(); } } public class Client { HttpClient client = new HttpClient(); public async Task HttpClientCallAsync() { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync("http://vendhq.com"); string responseAsString = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseAsString); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ajax中的application/x-www-form-urlencoded中的使用(转载)
- ios – 在Xcode 5.1.1中破坏了MoarFonts
- Oracle 表空间数据文件迁移图解
- 正则
- ajax – 调用remoteForm只用onChange事件更新一个div
- 使用Saxon在Altova XML中使用xsl:result-document的奇怪行
- c# – 从JavaScript提交按钮点击/页面提交
- 正则表达式 – 找到匹配后,文本文件中的sed内联替换句子
- 使用C# 的webBrowser写模拟器时的javascript脚本调用问题
- 关于Oracle 10.2.0.5 版本应用SCN补丁14121009相关问题