I have an array of strings. For each string I have to accomplish a task, and I want to do that in parallel. This is my piece of code:
void Test()
{
sourcefiles.AsParallel().ForAll(MyMethod);
}
private void MyMethod(string source)
{
string tmp_string = RandomString(10);
string path = Path.Combine(@"C:\myfolder", tmp_string);
// (File operations on `path` go here)
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
I receive the following exception: Cannot access C:\myfolder\ABCDEFG because it is in use by another process
which is weird because the string "ABCDEFG" should be a random one generated by different processes. This is not an unfortunate event, it happens all the time. I also increased the complexity of RandomString()
, but nothing happens, in fact I keep seeing from the debug that there are two different processes with the same tmp_string
(other processes have a different one). Where's the mistake?
For context, this is what happens:
PROCESS - RANDOM_STRING
1937 - "r6MbODsNcF1654683907030"
1374 - "MqrdQe386M1654683928872" <---
1518 - "iX33edEA5F1654683928873"
1691 - "MqrdQe386M1654683928872" <---
1486 - "u46vqUrt601654684013613"
the first 10 alphanumeric characters are from the RandomString()
function, the following digits represent the Unix's epoch
EDIT Some of you suggested that creating in rapid succession the class Random(), would generate the same seed. As some comment states, this is not true, at least in .NET (Core). It works fine either by workaround-ing it by using a lock, or by using the code in the accepted answer, since (as last as I understood) Guid is thread-safe.