访问另一个线程中方法返回的值

时间:2014-04-09 14:35:24

标签: c# multithreading return-value

如何访问由另一个线程中运行的方法返回的值?

让我们说:

public string[,] method1
{
    string a = "blah";
    return a;
}

private void btn_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(method1);
    thread.Start();

    // here I want to use a ...
    Label1.Text = a;
}

有人可以告诉我吗?

2 个答案:

答案 0 :(得分:3)

为什么不,

public Task<string> Method1()
{
    return Task.Run(() => "blah");
}

private async void btn_Click(object sender, EventArgs e)
{
    Label1.Text = await Method1();
}

或者,如果函数采用参数,

public Task<string> Method1(string someString, int someInt)
{
    return Task.Run(() => string.Format("{0}{1}", someString, someInt));
}

private async void btn_Click(object sender, EventArgs e)
{
    Label1.Text = await Method1("EZ", 1);
}

甚至,

private Task<string[][]> ArrayMaker(uint x, uint y)
{
    return Task.Run(() =>
    {
        var result = new string[x][]
        for (var i = 0; i < x; i++)
        {
            result[i] = new string[y];
            for (var j = 0; j < y; j++)
            {
                result[i][j] = ((long)i * j).ToString(
                    CultureInfo.InvariantCulture);
            }
        }

        return result;
    });
}


private async void btn_Click(object sender, EventArgs e)
{
    var bigArray = await ArrayMaker(1000000, 1000000);
}

答案 1 :(得分:0)

Label1.InvokeIfRequired(c => { c.Text = a; });

&#34; a&#34;是来自另一个线程的字符串或文本。