我如何强制自己超时?
我必须使用 API 来调用第三方,并且最好使用它返回的响应。 该 API 具有内置的 30 秒超时,并且不允许您以编程方式进行设置。 我需要它在 12 秒内超时。 这是我正在拨打的电话:
string response = theAPI.FunctionA(a, b, c, d);
我一直在想我可能需要使用异步调用来完成此任务并在 12 秒时中止线程。 另一个 stackoverflow 问题似乎与我正在考虑的问题很接近: Implement C# Generic Timeout
.. .我只是想知道这是否是最好的方法。 具体来说,我不断看到警告您无论如何都要调用 EndInvoke 的文章,我想知道引用示例中的 Abort 是否仍会适当地关闭线程? 我看到有一些评论对使用 Abort 非常担心。
I have to use an API to make a call to a third party, and ideally use the response it returns. The API has a built-in 30 second timeout, and does not allow you to set that programatically. I need it to time out in 12 seconds. Here's the call I'm making:
string response = theAPI.FunctionA(a, b, c, d);
I've been thinking I might need to use async calls to accomplish this and abort the thread at 12 seconds. Another stackoverflow question appears to come close to what I'm considering: Implement C# Generic Timeout
...I'm just wondering if this is the best way. Specifically, I keep seeing articles that warn you to call EndInvoke no matter what, and I'm wondering if Abort as in the referenced example will still close the thread appropriately? I see there were some comments with much concern about using Abort.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
中止线程通常是一个坏主意。 如果调用时间超过 12 秒,为什么不直接让调用完成(或在 30 秒后超时)而忽略结果(并继续)?
Aborting threads is generally a bad idea. Why not just let the call complete (or time out after 30 seconds) but ignore the result (and move on) if it takes more than 12 seconds?
当然,
Thread.Abort
将关闭线程,因为它将调用 Win32TerminateThread
。此操作的结果将取决于您的
API
希望如何被TerminateThread
关闭。如果您的方法被称为
NuclearPlant.MoveRod()
或Defibrillator.Shock()
之类的东西,我宁愿等待这 30 秒。此方法不让受害者有机会进行清理:
正如
MSDN
中所述:Thread.Abort
will close the thread, of course, as it will call Win32TerminateThread
.Outcome of this action will depend on how your
API
likes to be closed byTerminateThread
.If your method is called somthing like
NuclearPlant.MoveRod()
orDefibrillator.Shock()
, I'd rather wait these 30 seconds.This method gives no chance to the victim to do some cleanup:
As stated in
MSDN
: