Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...