Can I block () in closing? What does it look like in Lambdas and code output?

I read this question and read this answer

This is a really fantastic feature. This allows you to close access to something usually hidden, say, a private class variable, and let it control it in a controlled way as a response to something like an event.

You can mimic what you want easily by creating a local copy of the variable and using it.

Do we need to implement Lock () in this situation?

What does it look like?

According to Eric Lippert, the compiler makes the code look like this :

private class Locals
{
  public int count;
  public void Anonymous()
  {
    this.count++;
  }
}

public Action Counter()
{
  Locals locals = new Locals();
  locals.count = 0;
  Action counter = new Action(locals.Anonymous);
  return counter;
}

What will the Lambda look like, as well as the long code?

+3
source share
3 answers

, , lock .

, :

public static Action<T> GetLockedAdd<T>(IList<T> list)
{
    var lockObj = new object();
    return x =>
    {
        lock (lockObj)
        {
            list.Add(x);
        }
    }
}

, , ? : ?

  • object, .
  • IList<T>.

, . :

class LockedAdder<T>
{
    // This field serves the role of the lockObj variable; it will be
    // initialized when the type is instantiated.
    public object LockObj = new object();

    // This field serves as the list parameter; it will be set within
    // the method.
    public IList<T> List;

    // This is the method for the lambda.
    public void Add(T x)
    {
        lock (LockObj)
        {
            List.Add(x);
        }
    }
}

public static Action<T> GetLockedAdd<T>(IList<T> list)
{
    // Initializing the lockObj variable becomes equivalent to
    // instantiating the generated class.
    var lockedAdder = new LockedAdder<T> { List = list };

    // The lambda becomes a method call on the instance we have
    // just made.
    return new Action<T>(lockedAdder.Add);
}

?

+5

, .

, , .

+2

:

static Func<int> GetIncrementer()
{
    object locker = new object();
    int i = 0;
    return () => { lock (locker) { return i++; } };
}

, , - . ​​, .

+1
source

Source: https://habr.com/ru/post/1787378/


All Articles