如何循环异步?

我得到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

}

}

}

}

回答:

一做,这是如下的方式。

  • 使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();

}

以上是 如何循环异步? 的全部内容, 来源链接: utcz.com/qa/263994.html

回到顶部