使任务中的一个异步/等待DB调用? [英] Make an Async/Await db call within a Task?

查看:114
本文介绍了使任务中的一个异步/等待DB调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个以下列方式处理传入消息的WCF服务:

We have a WCF service that is processing incoming messages in the following manner:

public bool ProcessMessage(string message)
{
    var returnValue = GetReturnValue();

    Task.Run(() => {
        //do some things with the message
        UpdateDatabase();
        SendRepliesOverNetwork();
    });

    return returnValue;
}

在努力来处理许多消息成为可能,我们在这里添加的任务。我们希望到returnValue尽快返回给调用者,让工作做它的事。

In an effort to process as many messages as possible, we added the task here. We want to return the returnValue to the caller as quickly as possible and let the Task do its thing.

我的问题:是否有任何优势,使用的awaitable异步调用数据库和/或使用的答复在网络异步方法

我是持谨慎态度,因为我觉得这可能产生太多的上下文切换。我们已经看到使用负载下100+线程的应用程序。

I'm cautious, as I think this may create too much context switching. We're already seeing the app using 100+ threads under load.

推荐答案

首先,我建议你退后一步,真正问,如果早回来是一个好主意。你在做什么通常是危险的;你在做实际的处理之前会返回OK到客户端。这仅仅是一个好主意,如果你的客户知道的returnValue并不意味着操作完成,只有它完全在收到SendReplies认为。

First, I suggest you take a step back and really ask if returning early is a good idea. What you're doing is usually dangerous; you're returning the "OK" to the client before doing the actual processing. This is only a good idea if your client knows that "returnValue" doesn't mean the action is complete and only considers it complete upon receiving the "SendReplies".

这是说,是的,你应该看到使一切异步,你可以一些好处。如果所有的任务是非阻塞模式,你会得到更好的使用你的线程池(较少上下文切换)的。

That said, yes, you should see some benefit from making everything asynchronous that you can. If all your tasks are nonblocking, you'll get better use out of your thread pool (less context switching).

public bool ProcessMessage(string message)
{
  var returnValue = GetReturnValue();

  Task.Run(async () => {
    //do some things with the message
    await UpdateDatabaseAsync();
    await SendRepliesOverNetworkAsync();
  });

  return returnValue;
}

这篇关于使任务中的一个异步/等待DB调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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