【发布时间】:2012-03-08 18:15:57
【问题描述】:
基本上,我需要忙着等到一些 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;
}
所以,如果我有 8 个canidates,它将产生 8 个线程,每个线程都在寻找出现在网页上的 claim all。 found 是一个全局变量。一旦其中一个线程找到claim all,它们都应该保释。
我对这种方法有几个问题。首先,它是一个很好的方法。其次,每个线程会得到它自己的忙等待函数的“副本”。我的意思是,一个线程可以抢占另一个线程并更改该函数中的数据,还是每个线程都获得函数内部声明的变量的副本。请注意,这两个函数都在同一个对象内。
【问题讨论】:
-
有效的技术问题,但看起来像是试图在扑克或拍卖中作弊。
标签: c# .net multithreading thread-safety