18

A continuation of a question asked here :

In the aforementioned question I have the following function which returns an object of type Task (for incremental testing purposes) :

private static Task<object> GetInstance( ) {
    return new Task<object>( (Func<Task<object>>)(async ( ) => {
        await SimpleMessage.ShowAsync( "TEST" );
        return new object( );
    } ) );
}

When I call await GetInstance( );, the function is called (and I assume the task is returned since no exception is thrown) but then the task just sits there.

I can only guess I am doing this wrong then.

I do not want this function to return a task that is already running ( that is IMPERATIVE ).

How do I asynchronously run the task returned by this function?

5
  • 1
    You're awaiting on GetInstance, and that's why your method waits there. It's still an async call, as the thread can be released for that wait. I think you're mixing asynchronous execution with multitasking. Commented Dec 7, 2015 at 23:47
  • Unclear what you are looking for, but perhaps Asynchronous Lazy Initialization?
    – chue x
    Commented Dec 8, 2015 at 0:18
  • I don't quite understand why this is necessary, if you don't actually want to start getting the instance, why are you calling GetInstance() at that point in time? Perhaps you want something like Func<Task<object>> or Lazy<Task<object>> so you may defer the call to GetInstance().
    – Lukazoid
    Commented Dec 8, 2015 at 0:18
  • I need to hang onto the object without running it because the task needs to be one which can be cancelled. I need to monitor the running state to determine if it should be started, cancelled, restarted, or if I need to yell at the user for being stupid...
    – Will
    Commented Dec 8, 2015 at 0:19
  • It is expected for asynchronous methods to return a Task which will complete at some point in time without being explicitly started. I would maintain Func instances to create the tasks as and when required.
    – Lukazoid
    Commented Dec 8, 2015 at 0:24

4 Answers 4

16

To create a Task already started

Try creating the task like this:

Task.Factory.StartNew<object>((Func<Task<object>>) ...);

To create a Task without starting it

If you don't want the task started, just use new Task<object>(...) as you were using, but then you need to call Start() method on that task before awaiting it!

[Reference]

My recommendation

Just make a method that returns the anonymous function, like this:

private static Func<object> GetFunction( ) {
    return (Func<object>)(( ) => {
        SimpleMessage.Show( "TEST" );
        return new object( );
    } );
}

Then get it and run it in a new Task whenever you need it (Also notice that I removed the async/await from the lambda expression, since you are putting it into a Task already):

Task.Factory.StartNew<object>(GetFunction());

One advantage to this is that you can also call it without putting it into a Task:

GetFunction()();
4
  • Wait - Won't that START the task? I need to return the task without it starting, and then start it again. I thought I was pretty specific about that (If it doesn't start the task then it's fine but this looks like it returns a task that's already running to me...)
    – Will
    Commented Dec 8, 2015 at 0:01
  • Of course, I assumed that was what you wanted because you were awaiting it. Otherwise you should call Task.Start()?
    – Joanvo
    Commented Dec 8, 2015 at 20:11
  • I modified my answer, hope it helps
    – Joanvo
    Commented Dec 8, 2015 at 20:21
  • 3
    Given the complexity of the situation with which I am dealing this question is out of the scope of consideration (TL;DR : I was doing it wrong). However your answer is the correct approach for creating a task and returning it without starting it.
    – Will
    Commented Dec 8, 2015 at 22:18
9

You should never use the Task constructor (or Task.Start).

I do not want this function to return a task that is already running ( that is IMPERATIVE ).

So, you want to return some code that won't execute until you call it? That's a delegate, not a Task.

private static Func<Task<object>> GetInstance()
{
  return async () =>
  {
    await SimpleMessage.ShowAsync("TEST");
    return new object();
  };
}

When you're ready to execute it, call it just like any other delegate. Note that it returns a Task, so you can await the result:

var func = GetInstance();
// Delegate has not started executing yet
var task = func();
// Delegate has started executing
var result = await task;
// Delegate is done
11
  • Thank you - but there is more to this than what you think. I need the task because I need it to support task cancellation and restarting. I did not want to bog down the question with what I felt to be details not pertinent to the immediate question.
    – Will
    Commented Dec 8, 2015 at 1:39
  • @Will: This can work fine with cancellation. What exactly do you mean by "restarting"? Commented Dec 8, 2015 at 1:41
  • 3
    Why should one never use Task constructor or Start?
    – Incerteza
    Commented Dec 8, 2015 at 1:42
  • 1
    @アレックス: I explain in full on my blog (constructor and Start). Commented Dec 8, 2015 at 1:43
  • @StephenCleary : I mean that there is a long-running task in play which executes functions in the background. The task should be one that can be cancelled and started again with relative impunity. Using a Task seemed like the natural choice (given the presence of the CancellationTokenSource class (or whatever it's called I'm too tired to look it up...).
    – Will
    Commented Dec 8, 2015 at 1:44
5

You are stuck with a bad design there. I'll try to make something work for you under these constraints.

The only way to delay start tasks is to use the Task.Start method. (You also can use RunSynchronously but that doesn't really make use of any of the tasks features. At this point the task becomes an unthreaded lazy object.

So use the Task.Start method.

await does not start tasks. It waits for tasks that already run. Therefore await new Task(() => { }) always freezes forever.

Another problem here:

return new Task<object>( (Func<Task<object>>)(async ( ) => {
    await SimpleMessage.ShowAsync( "TEST" );
    return new object( );
} ) );

When you start that task it will complete nearly instantly and Task.Result will hold another task - the one returned by the async lambda. I doubt this is what you want. Hard to make this work and I don't know what you need.

This smells like the XY problem. Can you elaborate on what you want to accomplish? It feels like you have given yourself unnecessary constraints.

3
0

OK, I think I've figured this out. Please examine this code:

class Program
{
    public static void Main(string[] args)
    {
        // Only RUN the task as needed.  FooGet 
        // still allows you to generalize your task.
        Task.Run(() =>
        {
            dynamic value = FooGet();

            value.RunSynchronously();

            Console.WriteLine(value.Result.Result.ToString());
        });

        while (true) Thread.Sleep(100);
    }

    private static Task<object> FooGet()
    {
        var task = new Task<object>(() => {
            return asyncBar();
        });

        return task;
    }

    private async static Task<object> asyncBar()
    {
        // do work!
        return "Hello, world!";
    }
}
3
  • Why would you use dynamic when you know the type?
    – Lukazoid
    Commented Dec 8, 2015 at 0:22
  • For some reason the compiler would not recognize the nested Task<object>. Using dynamic allowed it to skip the compiler and at run time get to the second task result. Commented Dec 8, 2015 at 15:32
  • That's because FooGet() is creating and returning a Task<object> and not Task<Task<object>> (which is what it actually is).
    – Lukazoid
    Commented Dec 8, 2015 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.