2013-11-14 47 views
0

我的應用程序出現問題,使用WatiN編寫的C#代碼。 應用程序創建幾個線程,並且每個線程打開瀏覽器和相同的頁面。
該頁面由HTML選擇元素組成:
example of select element
和提交按鈕。
瀏覽器應該選擇一個特定的選項,並在同一時間點擊提交按鈕但他們做它「一個」。 這裏是主要行代碼:Watin多線程問題

[STAThread] 
static void Main(string[] args) 
{ 

    for (int i = 0; i < numOfThreads;i++) 
    { 
     var t = new Thread(() => RealStart(urls[i])); 
     t.SetApartmentState(ApartmentState.STA); 
     t.IsBackground = true; 
     t.Start(); 
    } 
} 

private static void RealStart(string url) 
    { 
     using (var firstBrowser = new IE()) 
     {     
      firstBrowser.GoTo(url); 
      firstBrowser.BringToFront();   
      OptionCollection options = firstBrowser.SelectList("Select").Options; 
      options[1].Select(); 
      firstBrowser.Button(Find.ByName("Button")).Click(); 
      firstBrowser.Close(); 
     } 
    } 

什麼的「一一」的選擇,而不是同時選擇的原因是什麼?

+0

我認爲該框架的一部分使用鎖...雖然沒有檢查。 – Kabbalah

+0

是否可以繞過或取消鎖定? @Kabbalah –

+0

否。因爲鎖用於使代碼線程安全。通過刪除它們,您將無法在多個線程中調用Button.Click。 同樣,我沒有實際檢查框架是否使用鎖。但這很可能是這種情況。 – Kabbalah

回答

0

解決方案:
經過長期的研究,我放棄了使用華廷此porpuse後。
相反,我創建了HttpWebRequest並將其發佈到特定的URL。
就像一個魅力:

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://domain.com/page.aspx"); 
ASCIIEncoding encoding = new ASCIIEncoding(); 
string postData = "username=user"; 
postData += "&password=pass"; 
byte[] data = encoding.GetBytes(postData); 
httpWReq.Method = "POST"; 
httpWReq.ContentType = "application/x-www-form-urlencoded"; 
httpWReq.ContentLength = data.Length; 
using (Stream stream = httpWReq.GetRequestStream()) 
{ 
    stream.Write(data,0,data.Length); 
} 
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse(); 
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

我同時發送這些請求,通過爲每個請求的線程。