HttpClient GetAsync 失败

Her*_*rro 3 c# web-services httpclient asp.net-web-api

我一直在尝试构建一个 Windows ConsoleApp 作为 WebService 运行来来回同步一些数据我已经构建了一个用于同步的项目,当我通过我的 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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

当它刚刚退出时,它会达到 Var response = Await 行。没有异常或任何警告,如果我正在调试它就会停止。

我的输出是:

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).
Run Code Online (Sandbox Code Playgroud)

我的网络服务控制器如下:

public IEnumerable<QaqcRow> Index(string username, string lastUpdated)
        {
            return GetFilteredList(username, lastUpdated).OrderBy(x => x.GetValue("FormId"));
        }
Run Code Online (Sandbox Code Playgroud)

我可以通过链接手动访问网络服务并获取数据,但是当我使用 httpclient 时它就会死掉。

Max*_*rdt 5

它过早退出程序,因为我猜它不会等待执行结束。(参见例如/sf/answers/1060488831/)

改变

public static async void Gettasks()
Run Code Online (Sandbox Code Playgroud)

到

public static async Task Gettasks()
Run Code Online (Sandbox Code Playgroud)

然后等待执行结束。

    static async void Main(string[] args)
    {
        await Gettasks();
    }
Run Code Online (Sandbox Code Playgroud)

编辑:咳咳,所以事实证明Main不能是异步的。因此,也许现在只需通过阻塞线程来确认该方法是否被正确调用,直到最后。

    static void Main(string[] args)
    {
        Gettasks();
        Console.ReadLine(); //just don't press enter immedietly :) 
    }
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以执行 `Gettasks().Wait()`。在“main”方法中执行此操作即可。 (3认同)