如何在此父方法中等待没有异步修饰符的异步方法? [英] How can I await an async method without an async modifier in this parent method?
问题描述
我有一个我想等待的方法,但是我不想引起多米诺骨牌效应,以为任何人都可以调用此调用方法并等待它。例如,我有这种方法:
I have a method that I want to await but I don't want to cause a domino effect thinking anything can call this calling method and await it. For example, I have this method:
public bool Save(string data)
{
int rowsAffected = await UpdateDataAsync(data);
return rowsAffected > 0;
}
我在打电话:
public Task<int> UpdateDataAsync()
{
return Task.Run(() =>
{
return Data.Update(); //return an integer of rowsAffected
}
}
这不起作用,因为我必须在方法中放入异步 Save()
的签名,然后我无法返回 bool
我必须将其设为 Task< bool>
,但我不希望有人等待 Save()
方法。
This won't work because I have to put "async" in the method signature for Save()
and then I can't return bool
I have to make it Task<bool>
but I don't want anyone awaiting the Save()
method.
是否有一种方法可以在没有async修饰符的情况下挂起代码,如await或以某种方式等待此代码?
Is there a way I can suspend the code execution like await or somehow await this code without the async modifier?
推荐答案
如何在此父方法中等待没有异步修饰符的异步方法?
How can I await an async method without an async modifier in this parent method?
问我如何使用C#编写应用程序,而又不依赖任何类型的.NET运行时?
That's kind of like asking "how can I write an application using C# but without taking a dependency on any kind of .NET runtime?"
简短的回答:不要那样做。
Short answer: don't do that.
真的,您在这里所做的是自然同步onous方法( Update
),通过在线程池线程( UpdateDataAsync
)上运行它来使其异步显示,然后您想要阻止它以使异步方法显示为同步状态(保存
)。严重的危险信号。
Really, what you're doing here is taking a naturally-synchronous method (Update
), making it appear asynchronous by running it on a thread pool thread (UpdateDataAsync
), and then you're wanting to block on it to make the asynchronous method appear synchronous (Save
). Serious red flags.
我建议您仔细研究Stephen Toub着名的一对博客帖子我应该为我的同步方法公开异步包装器和我应该为我的异步方法公开同步包装器。这两个问题的答案都是否,尽管史蒂芬·图卜(Stephen Toub)解释了如果确实需要这样做的几种选择。
I recommend you carefully study Stephen Toub's famous pair of blog posts should I expose asynchronous wrappers for my synchronous methods and should I expose synchronous wrappers for my asynchronous methods. The answer to both questions is "no", though Stephen Toub explains several options to do it if you really have to.
必须保留给应用程序级别。我假设这些方法(更新
, UpdateDataAsync
和保存
)位于应用程序的不同层(例如,数据/数据服务/视图模型)。数据/数据服务层不应进行同步/异步转换。视图模型(特定于应用程序)级别是唯一有借口进行这种转换的级别,并且只能在万不得已时使用。
That "really have to" should be reserved for the application level. I assume these methods (Update
, UpdateDataAsync
, and Save
) are in different layers of the application (e.g., data / data service / view model). The data / data service layers should not be doing synchronous/asynchronous conversions. The view model (application-specific) level is the only one that has an excuse to do that kind of conversion -- and it should only do so as a last resort.
这篇关于如何在此父方法中等待没有异步修饰符的异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!