In your case there is no viable work-around to this problem: by the time the Stream.MessageReceived
event fires, the count
may be well out of scope in the caller of your DoWork
function.
In situations like that you should encapsulate the count
in an object, and keep a reference to that object in both the event handler and in the caller, like this:
class Counter {
public int Value {get;private set;}
public void Increment() {Value++;}
}
void DoWork(Counter count) {
MessageStream Stream = new MessageStream();
Stream.MessageReceived += (o, args) => {
count.Increment();
};
}