如何从异步任务访问文本框

时间:2017-02-13 06:18:20

标签: c# visual-studio async-await httpclient

如何访问textbox并填写http请求收到的responseString

    public async void button1_Click(object sender, EventArgs e)
    {

        await RunAsync();
    }


    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            var values = new Dictionary<string, string>
            {
                { "token", "aez" },
            };

            var content = new FormUrlEncodedContent(values);

            var response = await client.PostAsync("localhost", content);

            var responseString = await response.Content.ReadAsStringAsync();
        }

    }

1 个答案:

答案 0 :(得分:1)

您可以使用Task<string>的结果中的字符串。

public async void button1_Click(object sender, EventArgs e)
{
    textbox.Text = await RunAsync();
}

static async Task<string> RunAsync() 
{
    using (var client = new HttpClient())
    {
        var values = new Dictionary<string, string>
        {
            { "token", "aez" },
        };

        var content = new FormUrlEncodedContent(values);

        var response = await client.PostAsync("localhost", content);

        return await response.Content.ReadAsStringAsync();
    }
}

或者您可以使RunAsync非静态,因此您可以使用this引用访问文本框。只需删除静态关键字并将值分配给方法中的文本框。

async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        var values = new Dictionary<string, string>
        {
            { "token", "aez" },
        };

        var content = new FormUrlEncodedContent(values);

        var response = await client.PostAsync("localhost", content);

        var responseString = await response.Content.ReadAsStringAsync();

        textbox.Text = responseString;
    }
}