如何安全地混合同步和异步代码? [英] How to safely mix sync and async code?

查看:20
本文介绍了如何安全地混合同步和异步代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个完全同步的库.它公开了同步方法,我有客户在使用它.

I have this library which is purely sync. It exposes sync methods and I have clients using it.

我将底层实现更改为异步并为任何想要使用它的人公开异步方法.但是现在我有很多复制的代码.异步代码似乎性能更好.我希望现有客户能够利用它,并希望消除代码重复.

I changed the underlying implementation to async and exposed async methods for whoever wants to use it. But now I have lots of replicated code. Async code seems to perform better. I'd like existing clients to take advantage of it and I want to eliminate code repetition.

是否有任何安全的方法来保持同步签名并调用异步实现?

Is there any safe way to keep a sync signature and call async implementation?

我特别害怕调用 .Result 和 .Wait 时出现死锁.

I'm specifically afraid of deadlocks when calling .Result and .Wait.

推荐答案

我强烈建议你不要这样做

首先阅读应该我公开异步方法的同步包装器?我应该为同步方法公开异步包装器吗? by Stephan Toub.

First, read Should I expose synchronous wrappers for asynchronous methods? and Should I expose asynchronous wrappers for synchronous methods? by Stephan Toub.

我不会这样做的主要原因:

The main reasons I wouldn't do this:

  1. 异步同步 - 正如你所说,死锁.在调用链的上层或下层,在异步上使用 ResultWait 可能是有风险的业务.这实际上取决于您运行的平台(ASP.NET、UI、控制台),因为每个平台的行为都有所不同(即使使用 ConfigureAwait(false))

  1. Sync over Async - As you said, deadlocks. Higher or lower down the call chain, using Result or Wait on async maybe risky business. It really depends on which platform you run (ASP.NET, UI, Console) as each one behaves a bit differently (Even when using ConfigureAwait(false))

Async over Sync - 可扩展性.一旦我看到一个异步端点,我就假设它是纯异步的,这对我来说,因为 API 的使用者意味着没有任何在我背后"旋转的线程.如果您的用户也有同样的假设,那么在尝试向外扩展时,如果您发现每次调用异步方法都使用线程池线程,则可能会严重损害性能.如果用户想用 Task.Run 包装一个同步方法,让他们自己去调用,并判断这将如何影响他们的应用程序

Async over Sync - Scalability. Once I see an async endpoint, I assume it is pure async, which for me, as the consumer of the API means there isn't any Thread spinning "behind my back". If your users assume the same, finding out that for every call to an async method a Thread Pool thread is used can drastically hurt performance when trying to scale out. If the users want to wrap a sync method with a Task.Run, leave it up to them to make that call and make their on judgement on how this will affect their application

这篇关于如何安全地混合同步和异步代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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