多线程-传递参数并接收结果

时间:2018-11-17 07:54:24

标签: c# multithreading winforms

我正在尝试各种使用线程的选项。我在下面编写了代码,但无法正常工作。如何修复代码,以便主功能可以正确显示产品?

using System;
using System.Threading;

namespace MultiThreads
{
    class Program
    {
        static int prod;
        public static void Main(string[] args)
        {
            Thread thread = new Thread(() => Multiply(2, 3));
            thread.Start();         
            for(int i = 0; i < 10; i++) { // do some other work until thread completes
                Console.Write(i + " ");
                Thread.Sleep(100);
            }
            Console.WriteLine();

            Console.WriteLine("Prod = " + prod); // I expect 6 and it shows 0
            Console.ReadKey(true);
        }

        public static void Multiply(int a, int b)
        {
            Thread.Sleep(2000);
            prod = a * b;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

忽略了您应该使用非阻塞任务,易失属性和其他协程主体的事实,您的程序无法按预期运行的直接原因是您没有将子线程重新加入到父线程中。参见Join

没有连接,Console.WriteLine(“ Prod =” + prod);发生在赋值prod = a * b;

之前
static int prod;
static void Main(string[] args)
{
    Thread thread = new Thread(() => Multiply(2, 3));
    thread.Start();
    for (int i = 0; i < 10; i++)
    { // do some other work until thread completes
        Console.Write(i + " ");
       Thread.Sleep(100);
    }
    thread.Join(); // Halt current thread until the other one finishes.
    Console.WriteLine();

    Console.WriteLine("Prod = " + prod); // I expect 6 and it shows 0
    Console.ReadKey(true);
}

public static void Multiply(int a, int b)
{
    Thread.Sleep(2000);
    prod = a * b;
}