My issue is that I have a List of strings, and I want to create one thread for one string, pass the string into the thread. This is my code:
public void getImageSource(List<string> UrlLinks)
foreach (string urlLink in UrlLinks)
{
开发者_如何学运维 ThreadStart myThread = delegate { Fetch(urlLink); };
Thread t = new Thread(myThread);
t.Priority = ThreadPriority.Lowest;
t.IsBackground = true;
t.Start();
}
public void Fetch(string Link)
{
MessageBox.Show(Link);
}
But all my messagebox return the same results, the first element in the List. How can I fix it? Thanks in advance.
You're running into the captured variable issue... you're capturing the urlLink
variable, not the value at the time that the delegate is created. The fix for this is to create a temporary variable inside the loop:
public void getImageSource(List<string> UrlLinks)
{
foreach (string urlLink in UrlLinks)
{
string urlCopy = urlLink;
ThreadStart myThread = delegate { Fetch(urlCopy); };
Thread t = new Thread(myThread);
t.Priority = ThreadPriority.Lowest;
t.IsBackground = true;
t.Start();
}
}
I wouldn't expect the first URL to be fetched multiple times though - it would be more likely that the last URL would be fetched (or some variety of URLs).
See Eric Lippert's blog post on this topic for more information.
精彩评论