2014-02-28 104 views
0

對於我的C#程序,我創建了下面的對象。從子類訪問主窗體

processurls processurls1 = new processurls(); 

後,我創造它,我點擊一個按鈕來開始我的計時器,它執行:

private void timer2_Tick(object sender, EventArgs e) 
{ 
    processurls1.pURLS(UrlList, URLCountOf, HTTP, label1, TotalURLS2, TotalURLS); 
} 

該定時器每500毫秒會觸發我processurls1對象的pURLS功能。 它會每次更新我的主表單標籤label1.text。 但我的問題是它只會更新標籤一次,我的程序運行非常笨重。什麼是安全的方式來傳遞標籤對象& picturebox對象到我的子類在主窗體上正確更新沒有滯後?

public void pURLS(List<string> UrlListOf, int Count, Images HTTP, Label label1, int TotalURLS2, int TotalURLS) 
{ 
    try 
    { 
     string WebResponse = HTTP.DoGET(UrlListOf[Count]); 
     string pattern = "href=\"(.*?)\""; 
     MatchCollection OtherURLS = Regex.Matches(WebResponse, pattern); 
     for (int i = 0; i < OtherURLS.Count; i++) 
     { 

      Match HasHttp = Regex.Match(OtherURLS[i].Value, "http"); 
      if (HasHttp.Success) 
      { 
       string CleanedUp = Regex.Replace(OtherURLS[i].Value, "href=\"", ""); 
       CleanedUp = Regex.Replace(CleanedUp, "\"", ""); 

       UrlListOf.Add(CleanedUp); 
       TotalURLS2++; 
      } 
      else 
      { 
       string CleanedUp = Regex.Replace(OtherURLS[i].Value, "href=\"", ""); 
       CleanedUp = Regex.Replace(CleanedUp, "\"", ""); 
       CleanedUp = UrlListOf[TotalURLS2] + "" + CleanedUp; 
       UrlListOf.Add(CleanedUp); 
       TotalURLS2++; 
      } 
     } 

     label1.Text = "U:" + TotalURLS2.ToString(); 
    } 
    catch (Exception) 
    { 
    } 
} 
+0

你應該做的第一件事就是要擺脫這一切,除了吃'catch'塊地看到,實際上可能任何錯誤發生。 –

回答

0

您需要了解異步基礎。

也許500毫秒不足以獲取/數據。除了使用定時器,只需要使用一個異步任務與該女士睡眠

在您的MainForm

public async Task UpdateMyLabels() 
{ 
    while (true) //change here by something more reliant 
    { 
     await processurls1.pURLS(UrlList, URLCountOf, HTTP, label1, TotalURLS2, TotalURLS); 
     Thread.Sleep(200); //ajust value here 
    } 
} 

在您的「裝表」事件:

{ 
     UpdateMyLabels(); 
} 

最後,添加「異步「關鍵字pUrls:

public async Task pURLS 
+0

不能等待'空'嗎? – Illuminati

0

將所有我的變量移入類本身。現在,我可以從我的BackgroundWorker訪問屬性和更新的主要形式有:d

static int ImageCount = 0; 
    static int currentImage = 0; 
    Images HTTP = new Images(); 
    List<string> UrlList; 
    static List<string> ImageCollection = new List<string>(); 

    public List<string> Images 
    { 
     get 
     { 
      return ImageCollection; 
     } 
     set 
     { 
      ImageCollection = value; 
     } 
    } 

    public int CurrentImage 
    { 

     get 
     { 
      return currentImage; 
     } 
     set 
     { 
      currentImage = value; 
     } 
    } 
    public int Count 
    { 
     get 
     { 
      return ImageCount; 
     } 
     set 
     { 
      ImageCount = value; 
     } 
    } 

    public List<string> URLS 
    { 
     get 
     { 
      return UrlList; 
     } 
     set 
     { 
      UrlList = value; 
     } 
    }