I have the following code:
class Program
{
class ProcessedEven
{
public int ProcessedInt { get; set; }
public DateTime ProcessedValue { get; set; }
}
class ProcessedOdd
{
public int ProcessedInt { get; set; }
public string ProcessedValue { get; set; }
}
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
IEnumerator<int> enumerator = Enumerable.Range(0, 100000).GetEnumerator();
Dictionary<int, ProcessedOdd> processedOddValuesDictionary = new Dictionary<int, ProcessedOdd>();
Dictionary<int, ProcessedEven> processedEvenValuesDictionary = new Dictionary<int, ProcessedEven>();
stopwatch.Start();
while (enumerator.MoveNext())
{
int currentNumber = enumerator.Current;
if (currentNumber % 2 == 0)
{
Task.Run(() =>
{
ProcessedEven processedEven =
new ProcessedEven { ProcessedInt = currentNumber, ProcessedValue = DateTime.Now.AddMinutes(currentNumber) };
await Task.Delay(100);
processedEvenValuesDictionary.Add(currentNumber, processedEven);
});
}
else
{
Task.Run(() =>
{
ProcessedOdd processedOdd =
new ProcessedOdd { ProcessedInt = currentNumber, ProcessedValue = Math.Pow(currentNumber, 4).ToString() };
await Task.Delay(100);
processedOddValuesDictionary.Add(currentNumber, processedOdd);
});
}
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.TotalSeconds);
Console.ReadKey();
}
So basically I have to iterate over an enumerator that is all the time synchronous.
Once the current value from the iterator is taken it gets processed, somehow in a way that takes a long time. After is processed depending on its value is being added to a dictionary. So in the end the dictionaries have to be populated with the right values.
In order to improve the speed I thought that introducing some parallelism could help, but after adding the "Task.Run" calls some
"System.NullReferenceException: 'Object reference not set to an instance of an object"
exceptions occured. Also the execution time increased compared to the "synchronous" version of this code (the one without the "Task.Run" calls).
I do not understand why these exceptions are being raised since everything seems not to be null.
Is there a way to improve the speed in this scenario (original code is without the "Task.Run" calls) by using multi threading ?
Should the addition of the processed elements to the dictionaries be done inside a lock statement, since the dictionaries seems to be shared between the tasks ?
