yield returns within lock statement

前端 未结 3 1090
不知归路
不知归路 2020-12-10 10:32

if i have a yield return in a lock statement does the lock get taken out on each yield (5 times in the example below) or only once for all the items in the list?

Tha

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 11:14

    @Lockszmith has a good catch (+1). I only post this since I find his code hard to read. This is a "community wiki". Feel free to update.

    object lockObj = new object();
    
    Task.Factory.StartNew((_) =>
    {
        System.Diagnostics.Debug.WriteLine("Task1 started");
        var l1 = GetData(lockObj, new[] { 1, 2, 3, 4, 5, 6, 7, 8 }).ToList();
    }, TaskContinuationOptions.LongRunning);
    
    Task.Factory.StartNew((_) =>
    {
        System.Diagnostics.Debug.WriteLine("Task2 started");
        var l2 = GetData(lockObj, new[] { 10, 20, 30, 40, 50, 60, 70, 80 }).ToList();
    }, TaskContinuationOptions.LongRunning);
    

    public IEnumerable GetData(object lockObj, IEnumerable list)
    {
        lock (lockObj)
        {
            foreach (T x in list)
            {
                System.Diagnostics.Debug.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " returned "  + x );
                Thread.Sleep(1000);
                yield return x;
            }
        }
    }
    

提交回复
热议问题