Lets 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 obviously to avoid fetching a page that is already scheduled for fetch. The filler object exposes an event that is subscribed via a lambda expression. My question is: can we say that the parameter npage is correctly handled in multithread scenario ? better: each event subscription receive its own npage parameter, or the last npage seen is propagate to all events ?
Variable capture happens per the declaration scope of
npage. The parameternpageis declared at the method level, and does not change within that method – so indeed, the use ofnpageis entirely thread-safe.The problem you are avoiding would occur if you were changing a variable within its declared scope, typically a loop – i.e.
however, by breaking it into a method you avoid this, i.e.