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

时间:2017-09-19 09:41:49

标签: c# entity-framework async-await

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

即使在向客户端发送数据后,我是否可以在c#代码和查询运行中使用await / 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
}

这是使用实体

加载数据时的一个问题
  

类型' System.Data.Entity.Core.EntityException'的例外情况   发生在mscorlib.dll中但未在用户代码中处理

     

其他信息:基础提供商在Open上失败。

实体代码,当我没有使用await-async

时工作正常

3 个答案:

答案 0 :(得分:2)

我们试试这个

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

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


return information;
}

返回任务,而不是字符串

答案 1 :(得分:0)

也许试试

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

这将使GetName函数保持在相同的上下文中。

此外,如果在GetName函数外部创建DbContext,则可以在执行UpdateActivity和SendNotification之前处理它,因为您无法等待GetName。为此,你需要返回Task,就像Dan建议的那样

答案 2 :(得分:0)

我认为那是因为dbContext在并行任务中不可用,因为您只将userId传递给并行任务,该任务最终引用dbcontext来执行dbOperation。您需要为此更改架构。

@extends('layouts.app')


@section('content')
<div class="container">
  {{$news->title}}<br/>
  @foreach($news->news_pictures as $news_picture)
    <img src="{{asset($news_picture->pictures)}}" width="200"><br/>
    @endforeach
   {!! $news->body !!} <br/>
  <small>written on{{$news->created_at}} by {{$news->user->name}} </small>


</div>


@foreach($news->news_comments as $news_comment)

  @if(!Auth::guest())
    <div class="well">
      <a href="{{action('ProfileController@show', [$news_comment->user->id, $news_comment->user->name])}}">{!! $news_comment->user->name!!}</a>
      {{$news_comment->comments}}<br/>
      {{$news_comment->created_at}}

    </div>
    @else
<div class="well">
  {{$news_comment->commentor}}<br/>
  {{$news_comment->comments}}<br/>
  {{$news_comment->created_at}}
</div>
    @endif

  @endforeach








@if(!Auth::guest())
  <form action="{{action('NewsController@AddComments',[$news->id])}}" method="post">
    {{csrf_field()}}
    <div class="container">
      <textarea type="text" class="form-control" name="comments" placeholder="your comment"></textarea>
      <button class="btn btn-primary" >post</button>
    </div>
  </form>


  @else
  <form action="{{action('NewsController@AddComments',[$news->id])}}" method="post">
    {{csrf_field()}}
    <div class="container">
      <input type="text" class="form-control" placeholder="your name" name="commentor">
      <textarea type="text" class="form-control" name="comments" placeholder="your comment"></textarea>
      <button class="btn btn-primary" >post</button>
    </div>
  </form>
  @endif
@endsection