I have some code which waits for a server response & uses a lambda to do stuff when it gets it. It also checks a class ivar, _timedOut, in this lambda, to see what to do. What I’m not sure of is, if _timedOut is changed somewhere else in the class after the lambda was created but before it’s invoked, what value of _timedOut will the lambda see?
I’ve trawled SO for answers to this, but none of the answers seem to address this specific query. Code –
public class MyClass
{
public MyClass()
{
_databaseService = //...database stuff
_uploadService = //...uploads info
_serverService = //...gets stuff from the server
_uploadService.UploadingStatusChanged += UploadStatusChanged;
}
private bool _timedOut = false;
private void GetFinalInfo()
{
FinalInfo finalInfo = _databaseService.GetFinalInfo();
if (finalInfo == null) // still have no finalInfo
{
_serverService.GetLatestFinalInfo((response, theFinalInfo) =>
{
if (!_timedOut) // this could be changed elsewhere in the class while we're waiting for the server response
{
if (response == ServerResponse.Successful)
{
_databaseService.AddFinalInfo(theFinalInfo);
// navigate to next screen
}
else
{
// do something else
}
}
});
}
else
{
// navigate to next screen
}
}
}
private void UploadStatusChanged(object s, MyEventArgs e)
{
// do stuff & call GetFinalInfo if good
}
Thanks for any help!
The lambda expression will be converted into an instance method, as you’re effectively capturing the
thisreference by virtue of referring to an instance variable (and you’re not capturing any of the local variables). The delegate created by the lambda expression will have a target ofthis, so when the delegate is executed, it will “see” any changes to_timedOut.Of course this is still subject to normal thread safety issues – if one thread changes the value of a variable, without any extra synchronization or memory barriers it’s possible for another thread to try to read that variable and see the old value.