[英]After passing variable to async method, how will setting variable to new instance in main thread affect async method?
For instance: 例如:
void SomeMethod()
{
MyObject o = new MyObject();
// Do stuff with o
SomeAsyncMethod(o);
o = new MyObject(); // Will this affect what was passed to SomeAsyncMethod?
}
Anything I do to 'o' will be obviously be apparent in both the main and the new thread. 我对'o'所做的任何事情在主线程和新线程中都显而易见。 However, if I set o equal to a new instance in the main thread it shouldn't change the fact the the variable in SomeAsyncMethod() is still pointing to the original instance of the object right? 但是,如果我将o设置为等于主线程中的新实例,则不应更改SomeAsyncMethod()中的变量仍指向对象的原始实例的事实吗?
No, it will have no effect on other o. 不,它对其他o没有影响。 however 然而
void SomeMethod()
{
MyObject o = new MyObject();
// Do stuff with o
SomeAsyncMethod(o);
o.Id = 2222; // will change objects Id property, which will
// be reflected in another thread
}
the reason is in your code you are changing value (reference) of local variable o, not the object itself 原因是你的代码中你正在改变局部变量o的值(引用),而不是对象本身
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.