Andzej Maciusovic
Andzej Maciusovic

Reputation: 4476

Use cases of .NET single Task Wait

I am wondering what is the use of creating "hot" task and waiting for it by blocking thread. Example:

Task.Run(() => DoWork()).Wait();

Because main thread will be blocked until task is not completed I would just run DoWork() in the main thread without event putting it in new task.

I saw this example in many places across internet (msdn also) and event found such code in our company projects. I can see it useful only if I want to pass cancellation token to running task.

Upvotes: 2

Views: 189

Answers (1)

Snoop
Snoop

Reputation: 1065

Imagine you've got some 3rd party API written by somebody else. Let's consider the following:

  1. You know there are bugs where sometimes the functions hang.
  2. You do not have the option to re-write the API yourself.
  3. Not enough time to re-write the API yourself.
  4. The API works good enough.

If any of the above statements are true then you may have a case where you'd create a task and wait for it to finish.

Let's take the first item for example where there is a bug that causes the API functions to hang... If you start a task and wait for the API function to complete (as follows) you don't run the risk of hanging your entire program based on an API that has issues.

ThirdPartyApi api = new ThirdPartyApi();
Task apiFunctionRunning = null;

// start the API's function running on it's own thread
apiFunctionRunning = Task.Run(() =>
{
    api.DoWork();
});

// wait for the API function to complete but also time-out if
// there is some problem where it hangs up (give it maybe 5s)
apiFunctionRunning.Wait(5000);

Upvotes: 3

Related Questions