基本上,我需要忙着等待一些 html 出现在网页上。我创建了以下代码来忙等我:
public void ExecuteBusyWaitThreads()
{
foreach (Canidate canidate in allCanidates)
{
Thread newThread = new Thread(delegate()
{
BusyWait(canidate);
});
newThread.Start();
}
}
public bool BusyWait(Canidate canidate)
{
//hit that url, and wait for the claim all button to appear
string page = null;
while (found == false)
{
HttpWebRequest request = Canidate.GetHTTPRequest(canidate.URL);
//make sure we add the authentication cookes to the request
request = Canidate.AddCookiesToRequest(request, canidate.GetCookies());
page = new Canidate().GetPage(request);
if (page.ToLower().Contains("claim all"))
{
found = true;
NotifyAllThreads();
}
}
return true;
}
所以,如果我有 8canidates
,它会产生 8 个线程,每个线程都在寻找claim all
显示在网页上。found
是一个全局变量。一旦其中一个线程发现claim all
,他们都应该保释。
我对这种方法有几个问题。首先,这是一个很好的方法。其次,每个线程都会获得自己的繁忙等待函数的“副本”。我的意思是,一个线程是否可以抢占另一个线程并更改该函数中的数据,或者它们每个线程都获取函数内声明的变量的副本。请注意,这两个函数都位于同一个对象内。
在回答你的问题之前,我必须指出你犯下了令人震惊的行为:关闭循环变量 http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx.
首先,这是一个很好的方法。
不,不是真的。任意创建线程通常不是一个好主意。最好使用线程池技术。这可以通过以下方式完成ThreadPool.QueueUserWorkItem
or the Task
class.
其次,每个线程都会获得自己的繁忙等待函数的“副本”。
我的意思是,一个线程可以抢占另一个线程并更改其中的数据吗?
该函数,或者它们每个都获得声明的变量的副本
函数内部。
每个运行实例BusyWait
将获得所有局部变量的自己的副本(即page
and request
)。自从found
在非本地范围中声明(大概无论如何),那么它将在所有正在运行的实例之间共享BusyWait
。因此,您当前的读取和写入操作found
不是线程安全的,因为没有同步机制。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)