In the last version C# there is the possibility paralleling calculations in a very simple way. Loop:
for (int n = 0; n < 8; n++) { Console.WriteLine("Normal - iteracja {0} wątek {1}", n, Thread.CurrentThread.ManagedThreadId); }[/code] <p style="text-align: justify;">can be replaced by the following structure:</p> [code lang="csharp"]Parallel.For(0, 8, i => { Console.WriteLine("Parallel - iteracja {0} wątek {1}", i, Thread.CurrentThread.ManagedThreadId); });
This provision should result in, that the calculations will be carried out in parallel. In my idea is great. One line replaces several lines of, which was written for Topics. In use Parallel.For it should be remembered, that the code will behave as a multi-threaded code to be executed, that is not known in what order will carry out the various stages of the loop. Additionally, be aware of the problem of sharing variables.
It should be noted, not always the individual that will perform operations in parallel. Sometimes there is simply no such need. By running this code one time can get the following results:
Parallel - iteracja 0 wątek 1 Parallel - iteracja 1 wątek 1 Parallel - iteracja 2 wątek 1 Parallel - iteracja 4 wątek 3 Parallel - iteracja 6 wątek 3 Parallel - iteracja 7 wątek 3 Parallel - iteracja 3 wątek 1 Parallel - iteracja 5 wątek 4
You can see here, that is not maintained the order in the loop, as well as calculations are performed for three different threads.
Another time, you can obtain the following result:
Parallel - iteracja 0 wątek 1 Parallel - iteracja 1 wątek 1 Parallel - iteracja 2 wątek 1 Parallel - iteracja 3 wątek 1 Parallel - iteracja 4 wątek 1 Parallel - iteracja 5 wątek 1 Parallel - iteracja 6 wątek 1 Parallel - iteracja 7 wątek 1
In this case, the calculations are done only by one thread, despite the absence of changes in the code.
Finally there remains the question of consideration of performance of this solution. What is faster, classical iterative approach, Threads, or Parallel.For. But this without testing it is impossible to check. And this is precisely the task for the coming period.
Leave A Comment