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