Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do Parallel computing using c#

I need to evaluate about 100k results and then save in a list because then I represent this on a chart.

But using only one thread is too long and I decided to use multithreading but I don't know anything about this.

This is the function that I use with a single thread:

for(int i=min;i<max;i++)
{
    list.Add(evaluate(expression, i));
}

I would like to do something like that but with multiple threads.

like image 441
Tinwor Avatar asked Aug 13 '26 00:08

Tinwor


2 Answers

You may want to look at the Task Parallel Library (TPL) and Parallel Programming in .NET Framework 4

The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

like image 162
Rahul Tripathi Avatar answered Aug 16 '26 21:08

Rahul Tripathi


Maybe something like this could help you.

var max = 100;
var min = 20;
var list = new MyResult[max - min];

Parallel.For(min, max, i =>
{
    list[i - min] = evaluate(expression, i);
});

Note that whatever evaluate does needs to be thread safe.

like image 39
Magnus Avatar answered Aug 16 '26 20:08

Magnus



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!