我还测试过,使用 new thread.....线程的方式调用,上面测试用 ref 传入的参数可以正常赋值,但据我了解,thread 里面不能安全更新UI界面。
首先,不要混淆Delegate的BeginInvoke 和 Control的BeginInvoke,这是两个完全不一样的东西。如果你要异步更新UI,那是 Control的BeginInvoke。关于Delegate的BeginInvoke,见http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.110).aspx。它有个Important说明,"No matter which technique you use, always call EndInvoke to complete your asynchronous call.",实际上那些ref和out的参数,都应该使用EndInvoke返回,它也给了个使用out的例子。
value是个局部变量,异步执行的时候它已经变成未定义了才对
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(value.ToString());
}
ref A
A = new A();
int b = 2;
ActionWithRef f3 = (int p1, ref int p2, string t) =>
{
p2 = 3;
Console.WriteLine("P2:" + p2);
Thread.Sleep(1000);
Console.WriteLine(t + " B:" + b);
};
f3.BeginInvoke(a, ref b, "异步", null, null); f3(a, ref b, "同步");
Console.ReadLine();刚试了下,比较有意思的是:如果没同步的那段,的确出来是2,一旦有了同步那段,出来一定是3,不管结果是同步的console出来还是异步的先console出来
int b = 2;
ActionWithRef f3 = (int p1, ref int p2, string t) =>
{
Console.WriteLine("P2:" + p2);
Thread.Sleep(1000);
p2 = 3;
Console.WriteLine(t + " B:" + b);
};
f3.BeginInvoke(a, ref b, "异步", null, null); f3(a, ref b, "同步");
Console.ReadLine();
又试了下这个步骤,不同点出来了,如果异步的先console,那么结果就是2,否则就是3
找到了这篇帖子,没解释原因,只说明要避免这样做法,打开网页后搜索下reference 就能找到这段说明了
怎么你等级这么高呢?