2014-01-12 70 views
-1

我得到List我需要循環瀏覽並花費在每一定時間的網站上。循環需要是異步的,因爲在每個網站上都會播放音樂,這就是要點 - 在這段時間聽到音樂,然後加載另一個頁面並聽音樂等等。此外,表單需要用於用戶操作。如何循環異步?

代碼到目前爲止我有是這樣的:

public void playSound(List<String> websites) 
{ 
    webBrowser.Navigate(Uri.EscapeDataString(websites[0])); 

    foreach (String website in websites.Skip(1)) 
    { 
     StartAsyncTimedWork(website); 
     // problem when calling more times 
    } 

} 

private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer(); 

private void StartAsyncTimedWork(String website) 
{ 
    myTimer.Interval = 7000; 
    myTimer.Tick += new EventHandler(myTimer_Tick); 
    myTimer.Start(); 
} 

private void myTimer_Tick(object sender, EventArgs e) 
{ 
    if (this.InvokeRequired) 
    { 
     this.BeginInvoke(new EventHandler(myTimer_Tick), sender, e); 
    } 
    else 
    { 
     lock (myTimer) 
     { 
      if (this.myTimer.Enabled) 
      { 

       this.myTimer.Stop(); 
       // here I should get my website which I need to search 
       // don't know how to pass that argument from StartAsyncTimedWork 


      } 
     } 
    } 
} 
+1

我只需要了解你想要做什麼:)你想在同一個線程中播放音樂,但在另一個線程中加載? 根據您的TickQuestion:http://stackoverflow.com/questions/13256164/send-a-extra-argument-in-dispatchertimer-tick-event ... – Softwarehuset

+0

@Softwarehuset假設時間總是5秒。所以我想在每個網站上播放音樂5秒鐘。當瀏覽器導航到網站時音樂會自動啓動,所以不用擔心。這意味着我需要以某種方式循環訪問網站,導航並在那裏停留5秒鐘,然後轉到下一個網站,但我無法停止使用Thread.Sleep()循環,聽不到。 – Tommz

+0

這個問題目前還不清楚。你將如何平行地聽音樂?你的意思是你想要在後臺加載網頁/音樂,所以歌曲之間沒有延遲?如果是這樣,那完全是另一個問題,並且一個沒有使用定時器解決的問題。 – theMayer

回答

1

一做,這是如下的方式。

  • 使websites一個類字段(如果它尚未),所以計時器事件處理程序可以訪問此集合。
  • 添加一個字段以跟蹤當前索引。
  • 添加一個字段以防止可重複調用PlaySounds
  • 您使用一個WinForms定時器,執行同一個線程的形式,所以沒有必要InvokeRequired

一些僞代碼(警告,這是未經測試):

private bool isPlayingSounds; 
private int index; 
private List<String> websites; 
private Timer myTimer; 

private void Form1_Load() 
{ 
    myTimer = new System.Windows.Forms.Timer(); 
    myTimer.Interval = 7000; 
    myTimer.Tick += new EventHandler(myTimer_Tick); 
} 

public void PlaySounds(List<String> websites) 
{ 
    if (isPlayingSounds) 
    { 
     // Already playing. 
     // Throw exception here, or stop and play new website collection. 
    } 
    else 
    { 
     isPlayingSounds = true; 
     this.websites = websites; 
     PlayNextSound(); 
    } 
} 

private void PlayNextSound() 
{ 
    if (index < websites.Count) 
    { 
     webBrowser.Navigate(Uri.EscapeDataString(websites[index])); 
     myTimer.Start(); 

     // Prepare for next website, if any. 
     index++; 
    } 
    else 
    { 
     // Remove reference to object supplied by caller 
     websites = null; 

     /Reset index for next call to PlaySounds. 
     index = 0; 

     // Reset flag to indicate not playing. 
     isPlayingSounds = false; 
    } 
} 

private void myTimer_Tick(object sender, EventArgs e) 
{ 
    myTimer.Stop(); 
    PlayNextSound(); 
}