在回调中获取threadstarter委托的返回值

时间:2017-04-06 18:42:40

标签: c# multithreading

我有一个简单的控制台应用程序,当它执行时:

1 - 在新线程中启动一个方法,一段时间后,在控制台中显示"生成值已完成"
2 - 立即显示"主线程已完成"

这是我的代码:

    static void Main(string[] args)
    {
        Start();
        Console.WriteLine("main thread is finished");
        Console.ReadLine();
    }

    private static int GenerateValue(int value)
    {
        int milliseconds = 10000;
        Thread.Sleep(milliseconds);
        return value*2;
    }

    private static void Start()
    {
        ThreadStart starter = () => GenerateValue(5);
        starter += () =>
        {
            Console.WriteLine("generate value is finished");
        };
        Thread thread = new Thread(starter) { IsBackground = true };
        thread.Start();
    }

我想要带来的改进是显示"生成值已完成",生成的值,例如此处" 10"。

但是我看不到如何在委托回调中访问" GenerateValue(5)"返回的值。 :

    starter += () =>
    {
       // Is it possible here to access to the value (that will be 10) 
       // returned by GenerateValue(5)
        Console.WriteLine("generate value is finished");
    };

1 个答案:

答案 0 :(得分:1)

你可以用一个闭包来实现这个目的:

private static void Start()
{
    int returnValue = 0;
    ThreadStart starter = () =>
    {
        returnValue = GenerateValue(5);
    };
    starter += () =>
    {
        Console.WriteLine("generate value is finished. Returned value is {0}", returnValue);
    };
    Thread thread = new Thread(starter) { IsBackground = true };
    thread.Start();
}