定期报告BackgroundWorker的进度 [英] Regularly report progress of a BackgroundWorker

查看:58
本文介绍了定期报告BackgroundWorker的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写音乐播放器.这是将目录添加到播放列表的(早期)代码:

I'm writing a music player. This is the (early) code that adds a directory to the playlist:

    private void SelectFolderButton_Click(object sender, EventArgs e)
    {
        int count = 0;
        AddFolderDialog.ShowDialog();
        if(AddFolderDialog.SelectedPath != string.Empty)
        {
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (a,b) => playlist.AddFolder(AddFolderDialog.SelectedPath, RecursiveCheckBox.Checked, out count);
            bgw.RunWorkerAsync();
            bgw.RunWorkerCompleted += (a, b) => mainStatusLabel.Text = "Added " + count + " songs"; ;
            bgw.RunWorkerCompleted += (a, b) => DrawPlaylist();
        }
    }

我刚刚开始使用线程.第一个问题是,这是正确的代码吗?这里有什么明显的错误吗?第二个问题是我想在添加歌曲时定期显示添加的歌曲数.不一定是逐首歌;每秒一次就可以了.我该如何实现?

I just started using threads. The first question is, is this a correct code? Is there something glaringly wrong here? The second issue is that I want to regularly display the number of added songs as they're being added. Not necessarily song-by-song; once a second is fine. How do I achieve this?

推荐答案

签出此SO线程.我用评论回答了另一个用户.从不同的线程更新MainWindow中的进度栏​​

Check out this SO thread. I answered that for another user with comments. Update progress bar in MainWindow from a different Thread

从本质上讲,您在后台工作人员中缺少了 WorkerReportsProgress = true ,并且还处理了 ProgressChanged 事件.另外,在设置所有事件之后,放置 RunWorkerAsync .

Essentially, you are missing WorkerReportsProgress = true in your background worker, as well as handling the ProgressChanged event. Also, put RunWorkerAsync after you set all your events.

如果您希望定期进行更新,则应改用DispatcherTimer,并将方法放在 Tick 事件中.

If you are looking at updating on regular intervals, you should use the DispatcherTimer instead, and place your methods within the Tick event.

这篇关于定期报告BackgroundWorker的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆