Passing a method parameter using Task.Factory.StartNew

前端 未结 5 770
灰色年华
灰色年华 2020-12-08 01:34

I have the following code:

var task = Task.Factory.StartNew(CheckFiles, cancelCheckFile.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

priv         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 02:10

    For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:

    foreach(int id in myIdsToCheck)
    {
        Task.Factory.StartNew( (Object obj) => 
            {
               var data = (dynamic)obj;
               CheckFiles(data.id, theBlockingCollection,
                   cancelCheckFile.Token, 
                   TaskCreationOptions.LongRunning, 
                   TaskScheduler.Default);
            }, new { id = id }); // Parameter value
    }
    

    You can learn more about it in my blog

提交回复
热议问题