Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary use thread-safe methods when i use AsParallel?

Tags:

c#

linq

When i use AsParallel(), the next operations runs in multi-thread, so, the methods that i use in this query, should be a thread safe?

In the next example, the method Convert(string value) is not thread-safe but is being used in a Select() that run as AsParallel().

Is it correct to use AsParallel() like standar Linq?

Note: The Convert() method it's just an example, but imagine a more complex method that really required a thread-safe implementation, when it will be executed in a multi-thread environment.

List<string> myNamesList = new List<string>()
{
   //Initialize with a lots of elements
}

List<string> myConvertedNameList = myNamesList.AsParallel()
                                               .Where("Any Condition")
                                               .Select(x => Convert(x)) 
                                               .ToList();
public string Convert(string value)
{
    int length = value.Length;
    string myFantasticValueConverted = "_" + value + "["+ length +"]";
    return myFantasticValueConverted;
}
like image 251
Gonzalo Martinez Avatar asked May 30 '26 22:05

Gonzalo Martinez


1 Answers

Is it necessary to use thread-safe methods when I use AsParallel?

Yes.

like image 154
Eric Lippert Avatar answered Jun 02 '26 11:06

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!