简体   繁体   English

当我使用线程运行 HttpClient.GetAsync(...) 并且它永远不会返回响应

[英]When I using a thread to run HttpClient.GetAsync(...) and it never returns response

I using a C# Console app to test Httpclient GetSync().我使用 C# 控制台应用程序来测试 Httpclient GetSync()。

When code run in getsync() and just close done my app.I need to get the response result.当代码在 getsync() 中运行并关闭完成我的应用程序时。我需要获取响应结果。 Is the thread and task await to conflict or the thread is not the main thread?是线程和任务 await 冲突还是线程不是主线程?

Where the code i misusing.我滥用代码的地方。

Program.cs程序.cs

using System;
using System.Threading;
using AutoProcessWorks;

_AutoProcessWorks autoProcessWorks = new _AutoProcessWorks();
Thread AutoRunThread = new Thread(new ThreadStart(autoProcessWorks.MainRun));
AutoRunThread.Start();

AutoProcessWorks.cs is here AutoProcessWorks.cs 在这里

public class _AutoProcessWorks
{
    Api api = new Api();
    SqlTools sqlTools = new SqlTools();
    public bool Switch_Run = true;
    public void MainRun()
    {
        int sleep = 60000;
        Api api = new Api();
        while (Switch_Run)
        {
            var route = "IsNFTContractEnough";
            var res = api.CallPythonApiGet(route);
            Console.WriteLine(res);
            Switch_Run = false;
        }
    }
public class Api
{
    public async Task<string> CallPythonApiGet(string route)
    {
        const string uri = "http://127.0.0.1:5000/";
        using (HttpClient client = new HttpClient())
        {
            var respones_result = "";
            try
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.Timeout = TimeSpan.FromSeconds(600);
                var response = await client.GetAsync(uri + route);
                respones_result = response.Content.ReadAsStringAsync().Result;
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
            }
            catch (HttpRequestException e)
            {
                var error = "";
                error += respones_result + "\n\r";
                error += "\nException Caught! Message :" + e.Message;
                return error;
            }
        }
    }
}

You are missing await all over the place, and you should not start a new thread, just call await MainRun()您到处都缺少await ,并且您不应该启动新线程,只需调用await MainRun()

_AutoProcessWorks autoProcessWorks = new _AutoProcessWorks();
await autoProcessWorks.MainRun();
public class _AutoProcessWorks
{
    Api api = new Api();
    SqlTools sqlTools = new SqlTools();
    public bool Switch_Run = true;

    public async Task MainRun()
    {
        int sleep = 60000;
        Api api = new Api();
        while (Switch_Run)
        {
            var route = "IsNFTContractEnough";
            var res = await api.CallPythonApiGet(route);
            Console.WriteLine(res);
            Switch_Run = false;
        }
    }
}
public class Api
{
    static HttpClient client = new HttpClient(); // keep only one of these around

    public async Task<string> CallPythonApiGet(string route)
    {
        const string uri = "http://127.0.0.1:5000/";
        var respones_result = "";
        try
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.Timeout = TimeSpan.FromSeconds(600);
            using var response = await client.GetAsync(uri + route);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
        catch (HttpRequestException e)
        {
            var error = respones_result + "\n\r" + "\nException Caught! Message :" + e.Message;
            return error;
        }
    }
}

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

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