一千萬個為什麽

搜索

C#lambdasのクラス変數のスコープ

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?

私はこれに答えるためにSOをトラウリングしましたが、答えのどれもこの特定のクエリに対処していないようです。コード -

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
}

助けてくれてありがとう!

最佳答案

_timeout will be part of the closure over the lambda.

ラムダの値が呼び出されたときの値 となることを意味します。

轉載註明原文: C#lambdasのクラス変數のスコープ