简体   繁体   中英

Value getting changed in the iteration before the call begins

I've the following code in my app.

MyEventHandler handler = null; //Declare the handler

foreach (string pname in group)
{
  handler = getHandler(pname); //Get the handler
  if(handler == null)
  {                        
      throw new KeyNotFoundException("No user " + pname + " could be found");
  }
  //invoke the handler
  handler.BeginInvoke(this, e, new AsyncCallback(EndAsync), null);
}

So i get the handler and call BeginInvoke method. But before BeginInvoke gets called it goes to next iteration and the handler value gets changed. So the BeginInvoke is getting involved for this new handler.

Hope you get my point. So how can i eliminate this issue? I dont want to call sleep after BeginInvoke as i feel it is a loss of time.

Any ideas?

Update1 I'm pretty sure that the handler object gets changed before BeginInvoke() is called. I guess that the BeginInvoke takes some time to create a separate thread to call the other function.

Update2 This code is in a WCF service and the clients call a function which in turn makes use of this function. I've separate handlers stored in my server for each client. The WCF service has a duplex contract with separates sessions for the client. I see that after this function is executed same user is getting invoked twice. But i put a break point and debug it (which gives the BeginInvoke the necessary time to call the function) it works "PERFECTLY". I very sure i faced this problem in threading too where i create multiple threads in a loop. If the thread delegate has parameters a,b,c and if you change it at the beginning of the next iteration the same behavior occurs. I dono how many of you people have experienced this issue before. If i put a Sleep() or if i make a copy of the handler and invoke it using copy it'll work.

Update3

Okie, i've tested it now. I just added the Thread.Sleep() as follows.

chatTo.BeginInvoke(this, e, new AsyncCallback(EndAsync), null);
Thread.Sleep(500);

and it is working like a charm. Any thoughts?

Update 4

I've created a thread sample demonstrating the issue and i've uploaded it here . I hope a solution to this will resolve my issue too. Kindly check the sample.

Ok, after your fourth edit you provide us with an example, that exhibits a problem, sure, but not the problem you're asking for help about .

What you're saying in the question is that:

  • I use BeginInvoke on a delegate variable, then change the variable, and somehow my delegates are invoked twice

What you exhibit in the posted code is that:

  • I capture a loop variable in an anonymous method, and somehow I use the wrong variable value

THESE ARE NOT THE SAME PROBLEM!

The reason for your posted code misbehaving is that the code in question actually looks like this under the hood:

int i;
for (i = 0; i < 10; i++)
    ... create delegate, capture i, spawn thread

Here you're capturing the same variable for all the threads. If a thread doesn't start executing before the loop changes the variable, then yes, you will see the "incorrect value" for that variable.

However, if you change the code like this:

for (int i = 0; i < 10; i++)
{
    int j = i;
    ThreadStart threadStartObj = new ThreadStart(
        delegate { PrintValueThreadFunction(j, j); });
                                            ^
                                            |
                                            +-- use j instead of i here

Then you will capture a "fresh" variable for each thread, which won't get changed.

So, the question remains. Is this the problem you're having? If so, then shame on you , next time, don't simplify the problem . You're wasting people's time, most of all your own. Had you posted code like the above to begin with you would've had an answer (or a duplicate question pointing to existing answers, there's plenty) within a couple of minutes.

If this is not the problem you're having, you're still having problem with an event handler like in the original code being invoked more than once, go back and produce a better example project.

I can't see why this would happen - the code you posted cannot possibly reproduce the behaviour you describe. It's entirely reasonable that the BeginInvoke call might not actual do anything straight away, and that the next iteration might occur before you actually see that call do anything - since it will be queued for processing by a worker thread.

This doesn't mean that a different handler is being invoked - the handler to be invoked is captured as soon as BeginInvoke is called, so it won't matter if the local variable changes afterwards .

Also - why have you got the lock here? Unless multiple threads are doing this processing at the same time over the same enumerable (in which case why would you do that) I can't see any reason why you would lock.

I would also say that if you're judging this behaviour by what you see in the debugger, then you shouldn't worry - you'll get 'interesting' results from the debugger by doing this, and with the multiple threads in the mix it's important to switch threads in the 'Threads' debugger window.

The question is - does your program actually do what you expect? If so, but you're seeing this strange behaviour whilst debugging - then that's entirely normal.

As a few comments have stated - the code you posted can't be exactly what's producing the problem. If, for example, 'handler' is a local variable shared between multiple threads that then perform this iteration then, yes, you could get something like this. But a variable local to a method can only be modified (and indeed read) by the same thread that's currently in that method ; the only exception to that rule being if the handler reference is then passed out to another threaded method as a ref .

我认为您还有其他问题... handler.BeginInvoke在下一次迭代后无法调用,您仍然在同一线程中...

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