如何通过局部变量获得线程结果?

abg*_*abg 2 .net c# lambda multithreading task-parallel-library

我试图通过局部变量获得线程结果.

有代码:

static void Main() 
{   
    long res1 = 0, res2 = 0;

    long n1 = 5000, n2 = 10000; 

    Thread t1 = new Thread(() => 
    { 
        res1 = Factorial(n1); 
    }); 

    Thread t2 = new Thread(() => { res2=Factorial(n2); }); 

    t1.Start();  
    t2.Start(); 
    t1.Join();  
    t2.Join(); 

    Console.WriteLine("Factorial of {0} equals {1}", n1, res1); 
    Console.WriteLine("Factorial of {0} equals {1}", n2, res2); 
} 
Run Code Online (Sandbox Code Playgroud)

输出:

Factorial of 5000 equals 0
Factorial of 10000 equals 0
Run Code Online (Sandbox Code Playgroud)

为什么这段代码返回0?

这是阶乘函数:

static long Factorial(long n) 
{ 
    long res = 1; 
    do 
    { 
        res = res * n; 
    } while(--n > 0); 

    return res; 
} 
Run Code Online (Sandbox Code Playgroud)

i3a*_*non 6

使用线程或变量捕获没有问题.您的Factorial方法只返回0,因为res = res * n快速溢出直到达到这些值:

long res = -9223372036854775808;
long n = 4938;

Console.WriteLine(res * n);
Run Code Online (Sandbox Code Playgroud)

您可以看到结果为0,如果我们围绕计算,checked我们将获得OverflowException:

long res = -9223372036854775808;
long n = 4938;

checked
{
    Console.WriteLine(res*n);
}
Run Code Online (Sandbox Code Playgroud)

当然,如果res变为0,则任何进一步的乘法也会导致0.

我不确定你要计算什么,但你可能需要一个不同的(更大的)数值数据类型(例如decimal)