我正在从 YouTube 检索 200 个视频 URL。但是它冻结了我的应用程序,我怎样才能使它工作,我也在后台工作人员中使用它,但仍然无法工作。
在此我使用了后台工作人员,我想在 listBox2 中添加视频标题。
初始化工人..
worker1 = new BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(worker1_DoWork);
worker1.ProgressChanged += new ProgressChangedEventHandler(worker1_ProgressChanged);
worker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker1_RunWorkerCompleted);
worker1.WorkerReportsProgress = true;
worker1.WorkerSupportsCancellation = true;
int ii = 0;
int jj = 0;
做功函数。
void worker1_DoWork(object sender, DoWorkEventArgs e)
{
int progressVal = 0;
textBox1.Invoke(new Action(
delegate()
{
if (worker1.CancellationPending)
{ return; }
string[] videoLink = textBox1.Text.Split(new char[] { '\n' });
progressBar1.Maximum = videoLink.Length ;
foreach (string s in videoLink)
{
string videoID;
try
{
videoID = s.Split(new char[] { '=' })[1].Trim();
}
catch (Exception ex)
{
MessageBox.Show(this, "Please enter correct video links\nExample : http://www.youtube.com/watch?v=123456789", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
YouTubeRequestSettings reqSettings = new YouTubeRequestSettings("Youtube Comments", devkey, usernames[jj], password) { Timeout = -1 };
YouTubeRequest request = new YouTubeRequest(reqSettings);
jj++;
if (jj == usernames.Length) jj = 0;
string commentContent = listBox1.Items[ii].ToString();
ii++;
if (ii == listBox1.Items.Count) ii = 0;
Comment comment = new Comment();
comment.Content = commentContent;
try
{
Video video = request.Retrieve<Video>(new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoID));
worker1.ReportProgress(progressVal++, "[" + comment.Content + "] Added to : " + "VideoTitle");
// request.AddComment(request.Retrieve<Video>(new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoID)), comment);
}
catch (Exception ex)
{
worker1.ReportProgress(progressVal++, "Error Accoured : " + "VideoTitle");
}
}
}));
}
我希望它每次在列表框中添加标题时都能取得进展,但它只在最后显示进度。完成整个过程后。
void worker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Value = progressBar1.Maximum;
this.Show();
}
void worker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
listBox2.Items.Add(e.UserState.ToString());
}