Gishu
Gishu

Reputation: 136653

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

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

Process.WaitForExit(timeout) on the other hand returns a boolean - true 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 ?

Upvotes: 2

Views: 408

Answers (2)

Gishu
Gishu

Reputation: 136653

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.

Upvotes: 2

Gabe
Gabe

Reputation: 86778

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.

Upvotes: 2

Related Questions