本文介绍了是否Task.RunSynchronously()的工作和QUOT;递归"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我称之为 RunSynchronously()工作在C#中,这还导致异步调用进一步下跌的兔子洞被同步运行呢?

让我们说我有一个名为方法 UpdateAsync()。在此方法中另一个异步调用,以 DoSomethingAsync()键,这里面我们再次找到 DoSomethingElseAsync(),将呼叫 RunSynchronously()在UpdateAsync()'导致 RunSynchronously()也间接地被要求 DoSomethingAsync()

的原因,我的问题:我有一个情况我需要来调用一个异步方法( UpdateAsync())一个抓在 - 块如果调用此与难怪RunSynchronously()是安全的。该文档是事实,你不能等待 A - 块里面很清楚。 (严格的说在try-catch后,我可以用一个布尔值的 - 块和呼叫 UpdateAsync()里面,但是,感觉比较脏)。很抱歉的双重问题,但你大概明白我不太知道如何句话并没有这个领域的一个很好的了解。

修改我不知道如何找出一个方法被称为异步。你会如何​​编写单元测试呢?是否有可能以某种方式记录吗?)

解决方案

有两种工作取值:code型* 任务(你可以创建这些通过使用工作构造函数或 Task.Factory.StartNew()),并承诺式任务 S(您可以通过使用 TaskCompletionSource 或通过编写异步方法手工创建)。

和唯一工作 s表示你就可以开始通过调用开始() RunSynchronously()尚未启动code型工作取值的。由于异步方法返回的承诺式的工作 S(或者可能已经开始code型工作 S),调用 RunSynchronously()对他们是无效的,并会导致异常。

因此​​,要真正回答你的问题:你在问什么是不可能的,所以也没有什么意义询问是否是安全的。


*这是不是一个正式的名字,我不知道是否有一个。

If I call RunSynchronously() on a Task in C#, will this lead to asynchronous calls further down the rabbit hole to be run synchronously as well?

Let's say I have a method named UpdateAsync(). Inside this method another asynchronous call is made to DoSomethingAsync() and inside this again we find DoSomethingElseAsync(), will calling RunSynchronously() on 'UpdateAsync()' lead to RunSynchronously() also indirectly being called on DoSomethingAsync()?

The reason for my question:I have a situation where I "need" to call an asynchronous method (UpdateAsync()) inside a catch-block and wonder if calling this with RunSynchronously() is safe. The documentation is quite clear on the fact that you can't await inside a catch-block. (Strictly speaking I could use a boolean inside the catch-block and call UpdateAsync() after the try-catch, but that feels rather dirty). Sorry about the dual question, but as you probably understand I don't quite know how to phrase it and do not have a really good understanding of this field.

(Edit:I don't know how to find out if a method was called asynchronously. How would you write a unit test for this? Is it possible to log it somehow?)

解决方案

There are two kinds of Tasks: code-based* Tasks (you can create those by using the Task constructor or Task.Factory.StartNew()) and promise-style Tasks (you can create them manually by using TaskCompletionSource or by writing an async method).

And the only Tasks that you can start by calling Start() or RunSynchronously() are unstarted code-based Tasks. Since async methods return promise-style Tasks (or possibly already started code-based Tasks), calling RunSynchronously() on them is not valid and will result in an exception.

So, to actually answer your question: what you're asking isn't possible, so it doesn't make sense to ask whether it's safe.


* This is not an official name, I don't know if there is one.

这篇关于是否Task.RunSynchronously()的工作和QUOT;递归"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:59