开发者

What is the recommended guideline or pattern for methods that can time out in .Net?

开发者 https://www.devze.com 2023-02-14 07:40 出处:网络
ServiceController.WaitForStatus(status, timeout) throws a TimeoutException if the operation doesn\'t complete.

ServiceController.WaitForStatus(status, timeout) throws a TimeoutException if the operation doesn't complete.

Process.WaitForExit(timeout) on the other hand returns a boolean - tr开发者_StackOverflow社区ue if the operation completes; else false.

Is there a recommendation going forward ?

A MSDN Connect forum post that I found leans towards the TimeoutException approach. Can someone please confirm ?


It all depends on the expected outcome. If some process is expected to timeout (e.g. waiting for user input), you make it a return code. If the timeout is likely the cause of an error (e.g. a network operation), you make it an exception. You could even have two versions: one that returns a value indicating whether it timed out and another that just throws an exception.


Found the elusive recommendation MSDN page.

A better approach is to use the TimeSpan structure as the time-out type. TimeSpan solves the problems with the integer time-outs mentioned above.

In addition, it is recommended that you throw an exception when a time-out expires instead of returning an error code. Expiration of a time-out means that the operation could not complete successfully and therefore should be treated and handled as any other run-time error.

In the case of an asynchronous operation with a time-out, the callback function should be called and an exception thrown when the results of the operation are first accessed.

Apparently you have to search with "time-out" while all the APIs use "timeout" as the name of the parameter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号