C#多线程 - 性能问题

时间:2018-04-23 21:32:05

标签: c# multithreading threadpool

我有控制台应用程序的数值计算,我试图使用ThreadPool并行。

我将对象状态作为类(简单数据传递):

public class DataContainer
{
    public double[,] Exa;
    public double[] EQ;
    public int iStart;
    public int iEnd;
}

WaitCallback的定义

private  void Calculate(object state)
{
    DataContainer data = state as DataContainer;

    for (int m = data.iStart; m < data.iEnd; m++)
    {
        double temp= 0.0;
        for (int i = 0; i < 500000; i++)
        {
            for (int j = i + 1; j < 500000; j++)
            {
                //Some-Long-Calculation based on data.Exa-around 200 math operation with results of double EQC
                if (EQC> temp) { temp= EQC; } //line performance issue-temp is declared in first for-loop block;
            }
        }
    }
}

执行:

WaitCallback waitCallback = Calculate;
const int numberOfThreads = 100;
ThreadPool.SetMaxThreads(30, 100);
for (int i = 0; i < numberOfThreads; i++)
{
    DataContainer tempContainer = new DataContainer();
    tempContainer.Exa = Exa; 
    tempContainer.EQ = EQ;
    tempContainer.iStart = CalculateStart(i);
    tempContainer.iEnd = CalculateEnd(i);

    ThreadPool.QueueUserWorkItem(waitCallback, tempContainer);
}

int numberOfTotalThreads = 0;
int numberOfMaxThreads = 0;
int numberOfWorkingThreads = 0;
int temp = 0;
//do-while - waiting to finish all calculation 
do
{
    ThreadPool.GetAvailableThreads(out numberOfTotalThreads, out temp);
    ThreadPool.GetMaxThreads(out numberOfMaxThreads, out temp);
    numberOfWorkingThreads = numberOfMaxThreads - numberOfTotalThreads;
    Console.WriteLine("Number of working threads {0}", numberOfWorkingThreads);
    Thread.Sleep(1000);
} while (numberOfWorkingThreads > 0);

所以有一条标记的行:

if (EQC> temp) { temp= EQC; }

计划的时间执行从40秒减慢到600秒。

你能否建议如何编写这些行以避免这个问题?

0 个答案:

没有答案
相关问题