串口同步模式和异步模式

    科技2022-08-01  118

    串口同步模式和异步模式

    It’s been a few months since we released UniTask v2, and we’re now at version 2.0.31, GitHub’s Star is achieved over 1100. We believe it is stable and will be used in production.

    从我们发布UniTask v2到现在已经有几个月了,现在我们的版本是2.0.31,GitHub的Star达到了1100以上。我们相信它是稳定的,可以在生产中使用。

    For more information on UniTask v2, see this article - UniTask v2 — Zero Allocation async/await for Unity, with Asynchronous LINQ.

    有关UniTask v2的更多信息,请参见本文-UniTask v2 —使用异步LINQ对Unity进行零分配async / await 。

    With the introduction of async/await, it is possible to implement new designs. Let’s take UnityWebRequest as an example of an asynchronous, pluggable and extensible design.

    通过引入异步/等待,可以实现新的设计。 让我们以UnityWebRequest作为异步,可插入和可扩展设计的示例。

    I will introduce it under the name async decorator pattern, but it is commonly known as Middleware.

    我将以异步装饰器模式的名称介绍它,但它通常称为中间件。

    It is a common design, mainly on the server side, implemented as a Filter in ASP.NET Core, Middleware in node.js (Express) and React, WSGI in Python, and MagicOnion. This is a very powerful design pattern and is also useful in client side.

    这是一种常见的设计,主要在服务器端,在ASP.NET Core中作为过滤器,在node.js(Express)和React中作为中间件实现,在Python中为WSGI和MagicOnion实现。 这是一种非常强大的设计模式,在客户端也很有用。

    For example, MagicOnion(our network framework, for .NET Core and Unity) works like this.

    例如, MagicOnion (我们的网络框架,用于.NET Core和Unity)的工作方式如下。

    The method is called from the outside to the inside, asynchronously.

    该方法是从外部到内部异步调用的。

    await next( await next( await next() ));

    If you want to extend UnityWebRequest, the required features are

    如果要扩展UnityWebRequest,则必需的功能是

    Logging

    记录中 Mocking

    模拟 Timeout

    超时 Processing request header before request

    在请求之前处理请求标头 Processing response header after request

    请求后处理响应头 Exception handling based on status code

    基于状态码的异常处理 UI handling after error (pop-ups, retries, scene transition)

    错误后的UI处理(弹出窗口,重试,场景转换)

    Everything can be implemented by async decorator.

    一切都可以由异步装饰器实现。

    装饰样本 (Decorator samples)

    The first step is to provide the following as a common interface.

    第一步是提供以下内容作为通用接口。

    Important thing is Func<RequestContext, CancellationToken, UniTask<ResponseContext>> next.

    重要的是接下来的Func <RequestContext,CancellationToken,UniTask <ResponseContext >>。

    Let’s take a look at some real use cases.

    让我们看一些实际的用例。

    As a simple example, it is handled before and after the header.

    作为一个简单的示例,它在标头之前和之后进行处理。

    We advance inside the decorator method that is chained by await next(). So if you write before it, it’s pre-processing, if you write after it, it’s post-processing.

    我们在装饰器方法内部前进,该方法由await next()链接。 因此,如果在它之前编写,则表示预处理,如果在它之后编写,则表示后期处理。

    Now, being integrated with async/await, try-catch-finally can be written naturally as well. For example, if you prepare a logging…

    现在,与async / await集成在一起,try-catch-finally也可以自然地编写。 例如,如果您准备日志记录…

    It’s also easy to terminate a process, just don’t call next. For example, you can create a decorator that returns a dummy response (to be used for testing or to proceed while the server-side implementation is not ready).

    终止进程也很容易,只是不要调用下一步。 例如,您可以创建一个装饰器,该装饰器返回一个虚拟响应(用于测试或在服务器端实现尚未准备好时继续进行)。

    Let’s also think about retry. For example, you receive a special response code that asks you to get a Token and reprocess it again.

    让我们考虑重试。 例如,您收到一个特殊的响应代码,要求您获取令牌并再次对其进行重新处理。

    If you want to put a queue in between to force sequential processing, you can write it like this

    如果要在两者之间放入一个队列以强制进行顺序处理,可以这样编写

    You can write easily from something simple to something that looks pretty complicated only provide async/await.

    您可以轻松地从简单的东西写到看起来很复杂的东西,只需提供异步/等待。

    This is how to use the prepared decorator.

    这是使用准备好的装饰器的方法。

    实现异步装饰器 (Implements async decorator)

    It’s a little longer, but it’s not so complicated.

    它稍长一些,但并不复杂。

    The core process is InvokeRecursive. To simplify it a bit more…

    核心过程是InvokeRecursive。 为了简化一点……

    Advancing IAsyncDecorator[], and “next” is the next element of the array(composed filter), and that’s the only implementation of this pattern.

    推进IAsyncDecorator [],“ next”是数组(组成过滤器)的下一个元素,这是此模式的唯一实现。

    Also, the NetworkClient itself is an IAsyncDecorator, which means that the one that doesn’t use next is the innermost part, the last part of the process.

    另外,NetworkClient本身是IAsyncDecorator,这意味着不使用下一个的是过程的最后一部分。

    A tip is that we handle the Timeout in CancellationTokenSource.CancelAfterSlim. Timeout can also be handled externally using WhenAny, but if the target has a CancellationToken argument, this is more efficient and better for terminate.

    提示是我们在CancellationTokenSource.CancelAfterSlim中处理超时。 超时也可以使用WhenAny从外部进行处理,但是如果目标具有CancellationToken参数,则终止的效率更高,并且更好。

    与场景过渡结合 (Combinate with scene transition)

    You know how when a network request fails, you get a pop-up that says something like, “An error has occurred, return to title, ‘OK’”? Let’s do that.

    您知道当网络请求失败时,如何弹出显示类似“出现错误,返回标题,'确定'”的弹出窗口? 来做吧。

    We can utilize UniTaskCompletionSource to express that we are waiting for the button to be pressed.

    我们可以利用UniTaskCompletionSource来表示我们正在等待按钮被按下。

    Now, let’s combine this with async decorator.

    现在,让我们将其与异步装饰器结合起来。

    It’s easy to write using await, so if you have the right tools, it’s not so easy to write asynchronous processing.

    使用await编写代码很容易,因此,如果您使用正确的工具,那么编写异步处理并不是那么容易。

    One thing you need to be aware of is whether or not to return to the caller. If you return normally, the processing will go back, but if you rethrow Exception, that will come up as an error. Since returning to the title screen means that the communication process has been cancelled, it’s correct to mark the process as cancelled here; to treat it as cancelled in the async method, you need to throw an OperationCanceledException.

    您需要注意的一件事是是否返回呼叫者。 如果正常返回,则处理将返回,但是如果您抛出Exception,则会出现错误。 由于返回标题屏幕意味着通讯过程已被取消,因此此处正确地标记为已取消是正确的; 要将其在async方法中视为已取消,则需要抛出OperationCanceledException。

    By utilizing async/await, you can achieve a design that is not possible with callbacks. Furthermore, with UniTask, there is no performance overhead.

    通过使用异步/等待,可以实现回调无法实现的设计。 此外,有了UniTask,就没有性能开销。

    We hope you will try to use UniTask as a base library for your games.

    我们希望您尝试将UniTask用作游戏的基础库。

    翻译自: https://medium.com/@neuecc/extends-unitywebrequest-via-async-decorator-pattern-advanced-techniques-of-unitask-ceff9c5ee846

    串口同步模式和异步模式

    相关资源:unity UniRx_5.5
    Processed: 0.010, SQL: 8