Kush
Kush

Reputation: 245

Variable Within Parallel. For

I have a Parallel For Loop, within that loop i have a dataset that holds data specific to the value returned from the parallel loop, as such:

    Parallel.For(0, uSet.Tables[0].Rows.Count, new ParallelOptions { MaxDegreeOfParallelism = val.MaxSubIterations() }, br =>
        {
            List<DataSet> MstWiseData = bll.GetUIDTable(uSet.Tables[0].Rows[0]["UID"].ToString());
            //Long Process Starts
        });//Uid Parallel

My Question is, does the MstWiseData variable get cleared on each loop, or is the data within it held until the loop completes and for another parallel loop, another instance of the same variable is created, i.e. loop on thread x has 2 datasets in the variable and loop on thread y has 4 datasets. Does the variable of Loop x get replaces by loop y?

Since i need to use that variable and dispose it once the Long Process is Completed.

Upvotes: 0

Views: 99

Answers (3)

Mez
Mez

Reputation: 4726

Your scenario is using Thread-Local variables, which are retrieved in each separate task that is created by the parallel For loop.

For more details view http://msdn.microsoft.com/en-us/library/dd460703.aspx.

Upvotes: 2

Hans Kesting
Hans Kesting

Reputation: 39358

The lambda expression is a different way of writing an anonymous method. Your MstWiseData variable counts as a local variable in that method, so every loop and thread uses a different one.

Upvotes: 1

Rob Lyndon
Rob Lyndon

Reputation: 12701

The former. It gets created and released on each iteration of the loop.

Upvotes: 0

Related Questions