c# - 如何在使用await async期间运行sql查询

标签 c# entity-framework async-await

在我的小项目中,我尝试保存一些数据或向用户发送通知。

我可以在我的 C# 代码上使用 wait/async 并在向客户端发送数据后运行查询吗?

这是示例:

async string GetName(long userId)
{
string information="";  // loading data with entity

await Task.Run(() => UpdateActivity(userId));
await Task.Run(() => SendNotification(userId));


return information;
}

void UpdateActivity(long userId)
{
// loading data with entity
// updating activity
}

void SendNotification(long userId)
{
// loading data with entity
// Sending Notification
}

这是我在使用实体加载数据时遇到的问题之一

An exception of type 'System.Data.Entity.Core.EntityException' occurred in mscorlib.dll but was not handled in user code

Additional information: The underlying provider failed on Open.

实体代码,当我没有使用await-async时工作正常

最佳答案

让我们试试这个

async Task<string> GetName(long userId)
{
string information="";  // loading data with entity

await Task.Run(() => UpdateActivity(userId));
await Task.Run(() => SendNotification(userId));


return information;
}

返回任务,而不是字符串

关于c# - 如何在使用await async期间运行sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46297050/

相关文章:

c# - 如何通过 UI 将参数传递给 NUnit 测试用例

c# - 如何在给定类名的情况下获取类的实例?

c# - Entity Framework 6 : The server was not found or was not accessible

c# - 执行多个数据库调用-单线程还是多线程?

c# - 使用 RTSP over TCP 进行流式传输

.net - Entity Framework 6 设置连接字符串运行时

c# - 测试数据库调用 C#

c# - 任务回调和 OnCompleted() 之间的区别

c# - 是否可以将异步方法声明为返回 void 以使 CS4014 警告静音?

c# - 初始化字符串的格式不符合从索引 50 开始的规范