1

I have created this code but trying to add some more function to it

public static int HowManyCores()
{
   int CoresNumber = Environment.ProcessorCount;
    try
    {
        return CoresNumber;
    }
    catch
    {
        return CoresNumber = 2;
    }
}

I want the function to return "2" if it failed for any reason. Also I would like to return CoresNumber -1 (So if it finds 4 it returns 3) also another case: if CoresNumer less than 2 (Including) return 2.

4

3 回答 3

1

Remove try catch and use

return CoresNumber > 2 ? CoresNumber - 1 : 2; 
于 2013-08-11T05:46:06.090 回答
1

As Vadim stated, it will not throw an exception. So you could try:

public static int GetCoreCount()
{
    int cores = Environment.ProcessorCount;

    if (cores <= 2) { return 2; }
    else { return cores - 1; }
}
于 2013-08-11T05:47:15.140 回答
0

i can give you this code:

public static int HowManyCores()
{
    int CoresNumber = -1;
    try
    {
        CoresNumber = Environment.ProcessorCount;
        if (CoresNumber <= 2) { CoresNumber = 2; }
    }
    catch
    {
        // Log maybe
    }

    return CoresNumber;
}

though you can read here that it shouldn't throw any exceptions

于 2013-08-11T05:49:13.097 回答