C# 创建新任务和异步调用web api c的正确方法#

C# 创建新任务和异步调用web api c的正确方法#,c#,api,asynchronous,async-await,task,C#,Api,Asynchronous,Async Await,Task,您好,我创建了两个示例,但我不确定这些示例是否正确。我想创建一个新任务并异步调用一个web api c# 第一个例子: private string APIResponse() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:55517/"); // Add an Ac

您好,我创建了两个示例,但我不确定这些示例是否正确。我想创建一个新任务并异步调用一个web api c#

第一个例子:

        private string APIResponse()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:55517/");
            // Add an Accept header for JSON format.  
            client.DefaultRequestHeaders.Accept.Add(new 
               MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("api/Values").Result;   
            if (response.IsSuccessStatusCode)
            {
                var products = response.Content.ReadAsStringAsync().Result;
                //Thread.Sleep(5000);
                return products.ToString();
            }
            else
            {
                return "ERROR";
            }
        }

        protected async void Apibtn_Click(object sender, EventArgs e)
        {
            Task<string> task = new Task<string>(APIResponse);
            task.Start();

            var ApiResp = await task;
            Do some work here... 
            // ...
            //..
            //.
        }
私有字符串APIResponse()
{
HttpClient=新的HttpClient();
client.BaseAddress=新Uri(“http://localhost:55517/");
//为JSON格式添加Accept标头。
client.DefaultRequestHeaders.Accept.Add(新建)
MediaTypeWithQualityHeaderValue(“应用程序/json”);
HttpResponseMessage response=client.GetAsync(“api/Values”).Result;
if(响应。IsSuccessStatusCode)
{
var products=response.Content.ReadAsStringAsync().Result;
//睡眠(5000);
返回产品。ToString();
}
其他的
{
返回“错误”;
}
}
受保护的异步void Apibtn\u单击(对象发送方,事件参数e)
{
任务任务=新任务(APIResponse);
task.Start();
var ApiResp=等待任务;
在这里做一些工作。。。
// ...
//..
//.
}
第二个例子是:

    private async Task<string> APIResponse()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:55517/");
        // Add an Accept header for JSON format.  
        client.DefaultRequestHeaders.Accept.Add(new 
                MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("api/Values");
        if (response.IsSuccessStatusCode)
        {
            var products = await response.Content.ReadAsStringAsync();
            //Thread.Sleep(5000);
            return products.ToString();
        }
        else
        {
            return "ERROR";
        }
    }

    protected async void Apibtn_Click(object sender, EventArgs e)
    {
        Task<string> task = APIResponse();
        // task.Start();  //You don't need to start the Tasks returned by 
                            async method calls. They're started by default.

        var ApiResp = await task;
        //Do some work here... 
        //...
        //..
        //.
    }
private异步任务APIResponse()
{
HttpClient=新的HttpClient();
client.BaseAddress=新Uri(“http://localhost:55517/");
//为JSON格式添加Accept标头。
client.DefaultRequestHeaders.Accept.Add(新建)
MediaTypeWithQualityHeaderValue(“应用程序/json”);
HttpResponseMessage response=wait client.GetAsync(“api/Values”);
if(响应。IsSuccessStatusCode)
{
var products=wait response.Content.ReadAsStringAsync();
//睡眠(5000);
返回产品。ToString();
}
其他的
{
返回“错误”;
}
}
受保护的异步void Apibtn\u单击(对象发送方,事件参数e)
{
任务=APIResponse();
//task.Start();//您不需要启动
异步方法调用。它们默认启动。
var ApiResp=等待任务;
//在这里做一些工作。。。
//...
//..
//.
}

如果以上都不正确,你能给我举个例子吗?谢谢第二个例子是正确的;决不能使用
任务结果


但是,最后不需要单独的
任务
变量;您可以直接等待呼叫。

您的第二个示例几乎正确,只需执行以下操作:

private async Task<string> APIResponse()
{
    using (HttpClient client = new HttpClient())
    {
        ...
        HttpResponseMessage response = await client.GetAsync("api/Values");
        ...
    }
}

protected async void Apibtn_Click(object sender, EventArgs e)
{
    var apiResp = await APIResponse();
}
private异步任务APIResponse()
{
使用(HttpClient=new HttpClient())
{
...
HttpResponseMessage response=wait client.GetAsync(“api/Values”);
...
}
}
受保护的异步void Apibtn\u单击(对象发送方,事件参数e)
{
var apiResp=等待APIResponse();
}

不要忘记
IDisposable
成员(如
HttpClient
)上的
使用
语句谢谢!你能举个例子吗?我会很感激的@Camiloterevento:这是一个事件处理程序;更具争议性的是,这可能是一个更好的帖子