I have code like this, some threads will generate string (here 100) and store to array, other single thread will read data using indexer [] and save to file. I used Interlocked class for string swapping in ThreadSafeString class but I don't know if its enough to avoid deadlocks and non thread safe problems. Other idea I have is to use ConcurrentDirectory<int, string> to be sure its safe.
using System;
using System.IO;
using System.Threading;
namespace Test
{
class ThreadSafeString
{
private string _string;
public string Value
{
get => Interlocked.CompareExchange(ref _string, null, null);
set => Interlocked.Exchange(ref _string, value);
}
}
class Program
{
private static readonly ThreadSafeString[] array = new ThreadSafeString[100];
static void Main(string[] args)
{
for (int i = 0; i < 100; i++) array[i] = new ThreadSafeString();
for (int i = 0; i < 100; i++)
{
var thread = new Thread(() =>
{
while (true)
{
string data = "";
//generate data
array[i].Value = data;
Thread.Sleep(100);
}
});
thread.Name = i.ToString();
thread.Start();
}
var ht = new Thread(() =>
{
while (true)
{
for (int i = 0; i < 100; i++)
{
string temp = array[i].Value;
File.WriteAllText(path, temp);
}
Thread.Sleep(2000);
}
});
ht.Start();
Console.ReadKey();
}
}
}
Enumerable.AsParallel()), the TPL,Parallel.For[Each],Tasks, take your pick. Manually gathering results from parallel computations is something you ideally should not want to bother with yourself.