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
@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;
}
}
}