Task.Run with Parameter(s)?

后端 未结 7 1961
生来不讨喜
生来不讨喜 2020-12-02 10:45

I\'m working on a multi-tasking network project and I\'m new on Threading.Tasks. I implemented a simple Task.Factory.StartNew() and I wonder how ca

7条回答
  •  伪装坚强ぢ
    2020-12-02 11:24

    Just use Task.Run

    var task = Task.Run(() =>
    {
        //this will already share scope with rawData, no need to use a placeholder
    });
    

    Or, if you would like to use it in a method and await the task later

    public Task SomethingAsync()
    {
        var task = Task.Run(() =>
        {
            //presumably do something which takes a few ms here
            //this will share scope with any passed parameters in the method
            return default(T);
        });
    
        return task;
    }
    

提交回复
热议问题