0

I have a problem with This code in C# :

main class {
var trick = new Object();
}
.......
public void AddTabWithCheck(List<Urls> url)
{

//Some Code 

foreach(Urls link in url){
     var thread = new System.Threading.Thread(p =>
        {
            lock (trick)
            {
                Action action = () =>
                {
                    addTab(link);
                };
                this.Invoke(action);
                if(link.Host == "google")
                    System.Threading.Thread.Sleep(5000);
            }
        });
        thread.Start(); }
}

I had problem to do a Time Delay in winapp form.

I coudnt use thread sleep , while(withDatetime) or similar becouse inside the WinAPP there is a WebControl Browser and i wish add some page in a loop with some delay time without freeze the UI. Neither timer is a good solution cause it's hard to handle for my situation.

So a User suggests me to use this Solution (the ones with Thread). I thought that it worked without problems but only now i realize that if i put in my loop it's take only last element (of loop) and create X threads all with the same element.

For a better explanation : i have this List<Urls> url ;

with this Class

public class Urls {
            public string Host { get; set; }
            public String url { get; set; }
}

Now i cant understand why if i add that code inside a simple Foreach , when the threads start all use the last element of loop.

I already checked if the List is correct , adding a MessageBox to show the current Object before the thread code , and it change properly.

Jasper
  • 311
  • 2
  • 5
  • 16

1 Answers1

2

All of your anonymous methods are sharing the same link variable.

You need to declare a separate variable inside the loop so that each method gets its own variable.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I just tried to Create Urls tmp = new Urls(); (before the loop) then inside the loop tmp=link; and i use tmp instead of link , but it's the same. I hope that was what you mean :) – Jasper Nov 23 '11 at 20:49
  • @Jasper: The first line in your foreach needs to be this: `var linkCopy = link;` and then you use `linkCopy` instead of `link`. – Austin Salonen Nov 23 '11 at 20:54
  • @Jasper No, `Urls tmp = link;` should be both declared and set within the loop. [Here's why.](http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx) – Chris Hannon Nov 23 '11 at 20:54
  • @Chris and Austin , Yes it works now. Thanks for The link, Chris. I'm going to read it now! I was thinking that i should create before the loop instead inside , but i was wrong. thanks – Jasper Nov 23 '11 at 20:59