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
a
will be independent of any external value. a
is too large to convert to a list and too expensive to get twice. 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.