在C#控制台应用程序中两个线程之间传递变量(我是新手)

3

我想知道如何在C#控制台应用程序中从一个线程发送变量到另一个线程。例如,

using System;
using System.Threading;

namespace example
{
    class Program
    {
        static void Main(string[] args)
        {
            int examplevariable = Convert.ToInt32(Console.ReadLine ());
            Thread t = new Thread(secondthread);
            t.Start();

        }

    static void secondthread()
    {
        Console.WriteLine(+examplevariable);
    }
}
}

我希望让"secondthread"识别"examplevariable"。
2个回答

3

有一个重载 Thread.Start() 接受一个参数为对象。你可以将你的主线程变量传递给它,并将其强制转换为你的变量类型。

    using System;
    using System.Threading;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int examplevariable = Convert.ToInt32(Console.ReadLine());
                Thread t = new Thread(secondthread);
                t.Start(examplevariable);
            }

            static void secondthread(object obj)
            {
                int examplevariable = (int) obj;
                Console.WriteLine(examplevariable);
                Console.Read();
            }

        }
    }

如果您想传递多个变量,则可以使用模型类,并像以下示例一样使用属性绑定。
using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TestModel tm = new TestModel();
            tm.examplevariable1 = Convert.ToInt32(Console.ReadLine());
            tm.examplevariable2 = Console.ReadLine();
            Thread t = new Thread(secondthread);
            t.Start(tm);
        }

        static void secondthread(object obj)
        {
            TestModel newTm = (TestModel) obj;
            Console.WriteLine(newTm.examplevariable1);
            Console.WriteLine(newTm.examplevariable2);
            Console.Read();
        }

    }

    class TestModel
    {
        public int examplevariable1 { get; set; }
        public string examplevariable2 { get; set; }

    }
}

希望这能有所帮助。

这似乎是起作用了,但我能否使用类似这样的方式进行多个变量转移? - LonelyPyxel
是的,您可以像这样传递变量数组而不是单个变量:int[] ar = new[] {1, 2, 3}; t.Start(ar); 并将其转换为 array int[] examplevariable = (int[]) obj; Console.WriteLine(examplevariable[2]);。通过这种方式可以传递多个变量。 - Mostafiz
请查看我的最新答案更新,这样您也可以传递多个变量。 - Mostafiz

1

一个简单的方法是在类上定义一个静态变量,并将从控制台读取的值赋给静态变量。但这种方法可能不适用于所有情况。代码如下:

class Program
{

    static int examplevariable;

    static void Main(string[] args)
    {
        examplevariable = Convert.ToInt32(Console.ReadLine ());
        Thread t = new Thread(secondthread);
        t.Start();

    }

    static void secondthread()
    {
        Console.WriteLine(+examplevariable);
    }

此外,查看如何向线程传递参数的问题:

带参数的ThreadStart


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接