gpt4 book ai didi

c# - 如何更改异步方法调用以防止强制调用堆栈异步

转载 作者:行者123 更新时间:2023-11-30 15:30:03 24 4
gpt4 key购买 nike

如果我需要调用一个方法,该方法又会在内部调用一些异步方法,作为即发即弃的操作,我如何才能防止此调用强制“异步”需要用完调用堆栈。 ..MVC Controller ?

例如:我的 MVC Controller (非异步)调用业务层方法,该方法又调用 Windows Azure 服务总线 QueueClient.SendAsync(BrokeredMessage),将消息放入队列中,但不需要等待让它完成。

通常,当调用此 Controller 操作时,编译器会抛出此时无法启动异步操作的错误。

我知道不是等待或只是调用 SendAsync() 方法,而是可以使用 ContinueWith() 跟进它,以便在异步操作的回调中执行代码,但我被告知这不是一个正确的解决方案。 (参见对 Calling async method in controller 的回复)

有人愿意告诉我解决这种情况的最佳方法吗?并告诉我为什么 ContinueWith() 方法不正确?

最佳答案

calls the Windows Azure Service Bus QueueClient.SendAsync(BrokeredMessage), to drop a message in a queue, but doesn't need to wait for it to complete.

首先,我会重新考虑这个假设。如果您想要一个完全可靠的系统,操作应该等待消息被发送到总线。请注意,这通常是一个快速操作(100 毫秒)。

Typically, when this controller action is invoked, the compiler will throw an error that the async operation cannot be started at this time.

确保您没有任何async void 方法或EAP method calls .如果 Azure 存储库导致该异常,我会感到非常惊讶。

Would someone care to enlighten me on the best way to fix this scenario? And tell me why the ContinueWith() approach is not correct?

最好的解决方案是拥抱asyncContinueWith 可以工作但使用起来很危险(它有很多参数,其中一些参数具有不安全的默认值); await 实际上与 ContinueWith 相同,但没有危险的默认值。


但是,如果 100ms 确实无法忍受,并且您愿意放弃可靠性(在这种情况下,这意味着您接受了一些消息可能不会发送到总线的事实,即使操作成功完成,因此客户端认为他们完成了),那么您可以使用 BackgroundTaskManager from my blog以尽量减少丢失消息的可能性。

关于c# - 如何更改异步方法调用以防止强制调用堆栈异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com