简体   繁体   中英

How can I run two methods on the one IEnumerable at the same time

Suppose I have

void MethodBoth(IEnumerable<int> a){
  Method1(a);
  Method2(a);
}

where both Method1 and Method2 call a foreach on a .

The problem here is that a will be recreated when passed to Method2 . Is there a way to get both methods to run simultaneously?

Suppose that

  1. For each i, the i-th entry of a will be independent of any external value.
  2. Other than that, I do not know how my method would be used, so I assume that a is too large to convert to a list and too expensive to get twice.
  3. I cannot edit the internals of Method1 or Method2 .

As proposed in the comments you can use threads and synchronization to achieve this:

var consumer1 = new BlockingCollection<int>(boundedCapacity: 1);
var consumer2 = new BlockingCollection<int>(boundedCapacity: 1);
var task1 = Task.Run(() => Method1(consumer1.GetConsumingEnumerable()));
var task2 = Task.Run(() => Method2(consumer2.GetConsumingEnumerable()));

foreach (var item in sourceCollection) {
 consumer1.Add(item);
 consumer2.Add(item);
}

consumer1.CompleteAdding();
consumer2.CompleteAdding();

Task.WaitAll(task1, task2);

I'm using BlockingCollection as a producer consumer handoff point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM