Whats wrong in this Parallel.For Code?

前端 未结 1 1200
别跟我提以往
别跟我提以往 2021-01-28 10:38

this is the code that i want to run.

Parallel.For(1, itemCount, 1, () =>
                    {
                     return new ThreadLocalStateCache()
                


        
1条回答
  •  情深已故
    2021-01-28 11:05

    The Parallel.For overloads that take step as the third argument were removed from .NET 4; see comments to http://blogs.msdn.com/b/pfxteam/archive/2009/05/26/9641563.aspx.

    Due to that, your call with 5 arguments is resolved to this overload:

    For(Int32, Int32, Func, Func, Action)
    

    And obviously the compiler cannot match types of the arguments.

    Since the step is 1 anyway, just remove it.
    Then you will need to fix the body delegate which must have three parameters (since thread local variable is now separate from loop state object), and add another delegate that will be applied to thread local variables for final computation. At the end, it should be something like this:

    Parallel.For( 1, itemCount,
                  () =>
                  { return new ThreadLocalStateCache() 
                               { 
                                   Receipient = serMailObj.ReceipientList.Dequeue(),
                                   mail = serMailObj.Email,
                                   client = client
                               }; 
                  },
                  (i, loopState, threadLocal ) => 
                  { 
                      doWork(i, threadLocal);
                      return threadLocal;
                  },
                  (threadLocal) => {}
                );
    

    0 讨论(0)
提交回复
热议问题