Home Dashboard Directory Help
Search

System.Threading.Tasks.Task.Wait() doesn't throw if not started by Brent Miller


Status: 

Closed
 as By Design Help for as By Design


1
0
Sign in
to vote
Type: Bug
ID: 691472
Opened: 9/28/2011 12:57:21 PM
Access Restriction: Public
Moderator Decision: Sent to Engineering Team for consideration
0
Workaround(s)
view
0
User(s) can reproduce this bug

Description

The following method should throw on Wait instead of block forever.

public static void Block()
{
    System.Threading.Tasks.Task bad = new Task<Int32>(() => 1);
    bad.Wait(); // i would want this to throw an exception to expose a programming error
}
Details
Sign in to post a comment.
Posted by Microsoft on 9/30/2011 at 7:54 AM
Hi Brent,

I can see how this behavior would be painful for you. However, given that we have the concept of "cold" (unstarted) Tasks, we must allow for the possibility that a Task can be started by someone other than the waiter, and therefore throwing an exception from UnstartedTask.Wait() is undesirable behavior. Consider a situation like this:

    Task A = new Task( () => {});
    Task B = new Task( () =>
    {
        Thread.Sleep(1000);
        A.Start();
    });

    B.Start();
    A.Wait();

At the time that A.Wait() is called, Task A will almost certainly not be started. But (at least in this case) Task A will eventually be started, so throwing an exception from the Wait() would be bad.

If it is the case for you that the waiter is always responsible for starting the Task, then you could write your own utility function to provide the behavior that you are seeking. Maybe something like:

    public void BrentWait(Task task)
    {
        if( (task.Status == TaskStatus.Created) ||
            (task.Status == TaskStatus.WaitingForActivation))
        {
            throw new Exception(...);
        }

        task.Wait();
    }

Hope that helps,
--Joe
Posted by MS-Moderator09 [Feedback Moderator] on 9/28/2011 at 10:43 PM
Thank you for submitting feedback on Visual Studio 2010 and .NET Framework. Your issue has been routed to the appropriate VS development team for review. We will contact you if we require any additional information.
Posted by MS-Moderator01 on 9/28/2011 at 1:43 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)
Sign in to post a workaround.