EF6 ToListAsync冻结Winforms [英] EF6 ToListAsync freezes Winforms

查看:340
本文介绍了EF6 ToListAsync冻结Winforms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Winforms应用程序,其上有一个按钮。首先使用EF 6.1.1代码,如果我在查询上使用.ToListAsync,它将冻结该表单,直到结果从SQL Server返回。

 code> private async void button1_Click(object sender,EventArgs e)
{
using(var context = new MyEFContext())
{
var result = await context。 MyTable.ToListAsync();
MessageBox.Show(result.Count);
}
}

如果我将.ToListAsync()调用放在不同的同步上下文通过添加等待Task.Delay(1).ConfigureAwaiter(false)之前,它应该是这样。



有人知道我在这里失踪吗?为什么是这样的?

解决方案

基本上,所有 async 同步到第一个等待



可能发生的情况是设置(打开连接等)太多时间。



您应该总是尽可能多地推送到UI线程之外。这样的东西:

  private async void button1_Click(object sender,EventArgs e)
{
this。 button1.Enabled = false;

var result = await GetMyTableAsync();

MessageBox.Show(result.Count);

this.button1.Enabled = true;
}

私有async任务< IList< MyTableEntity>> GetMyTableAsync()
{
using(var context = new MyEFContext())
{
return await context.MyTable.ToListAsync()
.ConfigureAwaiter(false);
}
}


I have a simple Winforms application with a button on it. Using EF 6.1.1 code first, if I use .ToListAsync on a query it will freeze the form until the result came back from the SQL Server.

  private async void button1_Click(object sender, EventArgs e)
  {
      using( var context = new MyEFContext() )
      {
         var result = await context.MyTable.ToListAsync();
         MessageBox.Show(result.Count);
      }
  }

If I put the .ToListAsync() call in a different synchronization context say by adding await Task.Delay(1).ConfigureAwaiter(false) before it, it works as it should be.

Does anybody know what I'm missing here? Why is it like this?

解决方案

Basically, all async code is synchronous until the first await.

What might be happening is the setup (opening connection and such) taking too many time.

You should always push as much as you can outside of the UI thread. Something like this:

private async void button1_Click(object sender, EventArgs e)
{
    this.button1.Enabled = false;

    var result = await GetMyTableAsync();

    MessageBox.Show(result.Count);

    this.button1.Enabled = true;
}

private async Task<IList<MyTableEntity>> GetMyTableAsync()
{
    using( var context = new MyEFContext() )
    {
        return await context.MyTable.ToListAsync()
             .ConfigureAwaiter(false);
    }
}

这篇关于EF6 ToListAsync冻结Winforms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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