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

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

问题描述

我有这个库,它是纯粹的同步。它暴露了同步的方法,我已经使用它的客户。

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

我改变了底层的实现,以异步和暴露的异步方法谁想使用它。但现在我有很多的复制code。异步code似乎有更好的表现。我想现有的客户能够利用它,我想要消除code重复。

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?

我特别怕死锁的要求。结果和.Wait时。

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

推荐答案

我强烈encourge您不这样做

I strongly encourge you not to do this

首先,请阅读我应该揭露同步封装为异步方法? 我应该公开异步包装器同步方法?通过斯蒂芬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 reason i wouldn't do this:

  1. 通过同步在异步 - 正如你所说,死锁。过高或过低下来的调用链,使用结果等待的异步也许风险的业务。这真的取决于你运行的平​​台(ASP.NET,UI,控制台)为每一个行为有点不同(即使使用 ConfigureAwait(假)

  1. With 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))

通过异步超过同步 - 可扩展性。有一次,我看到一个异步终端,我认为它是纯粹的异步,这代表我的API的消费者表示没有任何线程旋转在我背后。如果您的用户承担相同的,发现自己的每次调用异步方法线程池线程试图向外扩展时使用可以大大影响性能。如果用户想换一个同步的方法与 Task.Run 留出来给他们作出这一呼吁并让自己的判断这将如何影响他们的应用程序

With Async over Sync - Scalability. Once i see an async endpoint, i assume it is pure async, which on my behalf 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 out to them to make that call and make their on judgement on how this will affect their application

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

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