Lambda expression, external variables in multithreaded

Let's take this code:

public void Hit(int npage) { bool fetch = false; lock (pagesHit) { if (!pagesHit.Contains(npage)) { pagesHit.Add(npage); fetch = true; } } if (fetch) { pageFiller.Completed += (s, e) => { lock (pagesHit) { pagesHit.Remove(npage); } }; } } 

this function can be called from different threads. The goal is to avoid fetching a page that is already scheduled for retrieval. The filler object provides an event signed through a lambda expression. My question is: can we say that the npage parameter handles correctly in a multi-threaded script? better: each event subscription gets its own npage parameter, or does the last page viewed extend to all events?

+6
source share
2 answers

The capture variable occurs within the npage declaration npage . The npage parameter npage declared at the method level and does not change in this method - so using npage is completely thread safe.

The problem that you are avoiding would occur if you change the variable in the declared scope, usually this is a loop - i.e.

 for(int npage = 0; npage < 100 ; npage++) Foo( (s,e) => DoSomething(npage) ); // not safe; npage shared between all 

however, breaking it down into a method that you avoid this, i.e.

 for(int i = 0; i < 100; i++) Hit(i); ... void Hit(int npage) { Foo( (s,e) => DoSomething(npage) ); // safe; npage is per-call } 
+7
source

Each call to the Hit method will have different values ​​for the link on the page.

In other words, each thread calling this method will have its own page.

This is because for each thread that calls this method, its operations and the subscription of the event handler will take place in different areas, so the npage link will indicate the value of the area.

+2
source

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


All Articles