Multithreading and closures in .NET

后端 未结 3 1910
执笔经年
执笔经年 2021-01-02 00:31

If I have this:

public string DoSomething(string arg)
{
    string someVar = arg;
    DoStuffThatMightTakeAWhile();
    return SomeControl.Invoke(new Func<         


        
3条回答
  •  抹茶落季
    2021-01-02 01:07

    Local variables stored in the current thread's stack, so each thread will have its own stack and each own someVar variable in it.

    Since it would be different values in each thread

    new Action(() => someVar)); 
    

    will capture it's own value of someVar.

    Edit

    I was simply wrong saying that, as Eric pointed. See his answer for correct explanation.

提交回复
热议问题