我一直在尝试构建一个作为WebService运行的Windows来来回同步一些数据,我构建了一个用于同步的项目,当我在我的wpf项目中运行它时,它似乎是工作的,但它不是。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using QAQC_DataCommon.Models;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Gettasks();
}
public static async void Gettasks()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/QAQC_SyncWebService/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var response = await client.GetAsync("Tasks/?username=XXXXXX&LastUpdated=1/1/15");
if (response.IsSuccessStatusCode)
{
List<QaqcRow> ls = await response.Content.ReadAsAsync<List<QaqcRow>>();
foreach (QaqcRow qaqcRow in ls)
{
Debug.WriteLine(qaqcRow.GetValue("BusinessUnit"));
}
}
}
catch (Exception)
{
throw;
}
}
}
}}
当它刚刚退出时,它就会到达Var response =等候线。没有异常或警告,如果我正在调试,它只是停止。
我的产出是:
The thread 0x1414 has exited with code 259 (0x103).
The thread 0x16e4 has exited with code 259 (0x103).
The program '[9656] TestApp.vshost.exe' has exited with code 0 (0x0).我的webservice控制器如下:
public IEnumerable<QaqcRow> Index(string username, string lastUpdated)
{
return GetFilteredList(username, lastUpdated).OrderBy(x => x.GetValue("FormId"));
}我可以通过链接手动转到webservice,并获得数据,但是当我使用httpclient时,它就会死掉。
发布于 2016-01-14 23:47:18
它过早地退出了程序,因为它不会等待执行的结束。(见例如https://stackoverflow.com/a/15149840/5296568)
变化
public static async void Gettasks()至
public static async Task Gettasks()然后等待死刑的结束。
static async void Main(string[] args)
{
await Gettasks();
}编辑:嗯,原来Main不能是异步的。因此,也许现在只需通过阻塞线程来确认这个方法是否被正确地调用,直到结束。
static void Main(string[] args)
{
Gettasks();
Console.ReadLine(); //just don't press enter immedietly :)
}发布于 2022-05-15 06:03:17
非常奇怪的问题,但对我来说,我所调用的方法--其中包含http客户端的方法--并没有被期待:
在我的控制台应用程序中:
ExampleClass.DoWorkUsingHttpClient()将其改为等待方法解决了问题:
await ExampleClass.DoWorkUsingHttpClient()此外,我的类是这样设置的(sudo代码):
public async static ExampleClass
{
public async static Task DoWorkUsingHttpClient()
{
var httpClient = new HttpClient();
var result = await httpClient.GetAsync("https://www.example.com");
}
}https://stackoverflow.com/questions/34801720
复制相似问题