Reputation: 4476
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
Reputation: 1065
Imagine you've got some 3rd party API written by somebody else. Let's consider the following:
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