WinApp Form C# 中的多线程时间延迟
我在 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(); }
}
我在 winapp 形式中执行时间延迟时遇到问题。
我不能使用 thread sleep 、 while(withDatetime) 或类似的方法,因为 WinAPP 内部有一个 WebControl 浏览器,我希望在循环中添加一些页面,并有一些延迟时间,而不冻结 UI。这两个计时器都不是一个好的解决方案,因为它很难处理我的情况。
所以用户建议我使用这个解决方案(带有线程的解决方案)。 我认为它工作没有问题但直到现在我才意识到,如果我放入循环中,它只需要(循环的)最后一个元素并使用相同的元素创建X个线程。
为了更好的解释:我有这个List
现在我无法理解为什么
public class Urls {
public string Host { get; set; }
public String url { get; set; }
}
如果我在一个简单的 Foreach 中添加该代码,当线程开始时都使用循环的最后一个元素
我已经检查了列表是否正确,添加了一个 MessageBox 以在线程代码之前显示当前对象,并且它正确更改。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有匿名方法都共享相同的
link
变量。您需要在循环内声明一个单独的变量,以便每个方法都有自己的变量。
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.