How to construct a Task without starting it?

前端 未结 3 1460
死守一世寂寞
死守一世寂寞 2020-12-15 14:56

I want to use this Task constructor. I can\'t seem to get the syntax right. Could someone correct my code?

Also, am I right thinking that

相关标签:
3条回答
  • 2020-12-15 15:47
       //creating task
       var yourTask = Task<int>.Factory.StartNew(() => GetIntAsync("3").Result);
    
       //...
    
       int result = yourTask.Result;
    

    UPDATE:

    Yes, unfortunately it does start the task. Use code as mentioned above instead:

       //creating task
       var yourTask = new Task<int>(() => GetIntAsync("3").Result);
    
       //...
    
       // call task when you want
       int result = yourTask.Start();
    
    0 讨论(0)
  • 2020-12-15 15:50

    To use the Task constructor that accepts an object state argument you must have a function that accepts an object argument too. Generally this is not convenient. The reason that this constructor exists is for avoiding the allocation of an object (a closure) in hot paths. For normal usage the overhead of closures is negligible, and avoiding them will complicate your code for no reason. So this is the constructor you should use instead:

    public Task (Func<TResult> function);
    

    ...with this lambda as argument:

    () => GetIntAsync("3")
    

    There is one peculiarity in your case though: the lambda you pass to the constructor returns a Task<int>. This means that the generic type TResult is resolved to Task<int>, and so you end up with a nested task:

    var t = new Task<Task<int>>(() => GetIntAsync("3"));
    

    Starting the outer task will result to the creation of the inner task. To get the final result you'll have to use the await operator twice, one for the completion of the outer task, and one for the completion of the inner task:

    static async Task Main(string[] args)
    {
        var outerTask = new Task<Task<int>>(() => GetIntAsync("3"));
        //...
        outerTask.Start(); // or outerTask.RunSynchronously() to use the current thread
        //...
        Task<int> innerTask = await outerTask; // At this point the inner task has been created
        int result = await innerTask; // At this point the inner task has been completed
    }
    
    0 讨论(0)
  • 2020-12-15 15:51
    var t = new Task<int>(() => GetIntAsync("3").Result);
    

    Or

    var t = new Task<int>((ob) => GetIntAsync((string) ob).Result, "3");
    

    To avoid using lambda, you need to write a static method like this:

    private static int GetInt(object state)
    {
       return GetIntAsync(((string) state)).Result;
    }
    

    And then:

    var t = new Task<int>(GetInt, "3");
    
    0 讨论(0)
提交回复
热议问题