调用Task.Result时Windows窗体中断 [英] Windows form breaks when calling Task.Result

查看:64
本文介绍了调用Task.Result时Windows窗体中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows窗体中具有类似于以下代码:

I have code similar to following inside my Windows form:

private async Task<string> GetGreetingAsync()
{
    return await Task.Run(() => "Hello");
}

private void button1_Click(object sender, EventArgs e)
{
    var x = GetGreetingAsync().Result;
}

单击该按钮将导致整个Windows窗体冻结并变得无响应.没有异常.

Clicking the button causes the entire Windows form to freeze and become unresponsive. No exception is thrown.

即使我不直接在事件处理程序中使用任务.Result,并且整个async标记的代码都在某些类库函数中(该类库提供不带async的接口),仍然会出现问题.此类类库的单元测试顺利通过,但是当我从Windows窗体上的事件处理程序调用其函数时,它中断并且没有响应.

Even when I don't use the task .Result directly in the event handler and the whole async marked code is in some class library function, which provides interface without async, the problem still occurs. Unit tests for such class library pass without any problems, but when I call its function from event handler on Windows form, it breaks and does not respond.

为什么会这样?我该如何解决?

推荐答案

您正在使用.Result;阻止UI线程(请参见ConfigureAwait)

You are blocking the the UI thread with .Result; (see ConfigureAwait)

private async Task<string> GetGreetingAsync()
{
    return await Task.Run(() => "Hello").ConfigureAwait(false);
}

private void button1_Click(object sender, EventArgs e)
{
    var x = GetGreetingAsync().Result;
}

一路异步

private async Task<string> GetGreetingAsync()
{
    return await Task.Run(() => "Hello");
}

async private void button1_Click(object sender, EventArgs e)
{
    var x = await GetGreetingAsync();
}

使用此版本,您甚至无需在GetGreetingAsync

Using this version you don't even need to await in GetGreetingAsync

private Task<string> GetGreetingAsync()
{
    return Task.Run(() => "Hello");
}

async private void button1_Click(object sender, EventArgs e)
{
    var x = await GetGreetingAsync();
}

这篇关于调用Task.Result时Windows窗体中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆