首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在一个用户界面中管理任务进度

在一个用户界面中管理任务进度
EN

Stack Overflow用户
提问于 2013-05-15 09:17:04
回答 1查看 178关注 0票数 0

我有一个应用程序,用户可以启动任务,繁重的任务。我希望在一个用户界面网格中管理这些任务的进度(每行都是一个任务,并有一个进度栏),用户可以通过单击一个按钮(使用主线程)显示这个网格。我遇到的问题是交叉线程操作。我知道原因:每当任务进度发生变化(使用thread1)时,算法都会尝试更新网格数据源(使用主线程)。但我不知道怎么解决。

我的网格的DataSource属性设置为BindingList<BackgroundOperation>

我的任务(BackgroundOperation)的定义

代码语言:javascript
复制
public class BackgroundOperation
{
    public int progression;
    public int Progression
    {
        get { return progression;}
        set
        {
            progression = value;
            OnPropertyChanged("Progression");
        }
    }

    public event EventHandler OnRun;
    public event EventHandler<ProgressChangedEventArgs> OnProgressChanged;
    public event PropertyChangedEventHandler PropertyChanged;

    public void Run()
    {
        var task = new Task(() =>
        {
            if (OnRun != null)
                OnRun(this, null);
        });

    task.Start();
    }

    public void ReportProgress(int progression)
    {
        Progression = progression;

        if (OnProgressChanged != null)
            OnProgressChanged(this, new ProgressChangedEventArgs { Progression = progression });
    }


    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-15 09:55:18

您需要在UI线程上运行OnProgressChanged (应该将BTW称为ProgressChanged)。您可以这样做:在创建类时保存SynchronizationContext,然后在那里对委托进行Post()

代码语言:javascript
复制
public class BackgroundOperation
{
    private readonly SynchronizationContext m_synchronizationContext;

    public BackgroundOperation()
    {
        m_synchronizationContext = SynchronizationContext.Current;
    }

    …

    public void ReportProgress(int progression)
    {
        Progression = progression;

        var handler = OnProgressChanged;
        if (handler != null)
            m_synchronizationContext.Post(
                _ => handler(
                    this,
                    new ProgressChangedEventArgs { Progression = progression }),
                null);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16561172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档