0

如何在演示者中设置 System.Timers.Timer 以便在视图线程中消逝?

环境:C#、.NET 4.0 CP、WinForms

我现在的鳕鱼在这里,但它不起作用。我必须在视图中另外“调用”。

我将视图投射到 ISynchronizeInvoke 以构建代码。投射到控制没有帮助。

public class GeneratorPagePresenter : IGeneratorPagePresenter
{
    private IGeneratorPage view;
    private Timer timer;

    public void SetView(IGeneratorPage generatorPage)
    {
        view = generatorPage;

        timer = new Timer();
        timer.Interval = 1000;
        timer.AutoReset = true;
        timer.SynchronizingObject = (ISynchronizeInvoke) view;
        timer.Elapsed += Timer_Elapsed;
    }

    void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        view.UpdateProgress(percentage);
    }
}

编辑

感谢 AnPasant 评论(神秘地消失了)。我将 SynchronizingObject 设置为参数。它工作正常,但代码看起来有些奇怪。

    public void SetView(IGeneratorPage generatorPage, ISynchronizeInvoke sync)
    {
        view = generatorPage;

        timer = new Timer();
        timer.Interval = 1000;
        timer.AutoReset = true;
        timer.SynchronizingObject = sync;
        timer.Elapsed += Timer_Elapsed;
    }

这个方法被 View 调用如下:

        presenter.SetView(this, this);
4

1 回答 1

0

问题是您必须在某处切换同步上下文。这种情况下的 ViewModel 应该在 UI Thread 中创建。

private IGeneratorPage view;
private Timer timer;
private SynchronizationContext uiSyncContext;

public GeneratorPagePresenter()
{
    uiSyncContext = SynchronizationContext.Current;
}

public void SetView(IGeneratorPage generatorPage)
{
    view = generatorPage;

    timer = new Timer();
    timer.Interval = 1000;
    timer.AutoReset = true;
    timer.Elapsed += Timer_Elapsed;
}

void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    uiSyncContext.Post((state) => view.UpdateProgress(percentage), null);                
}
于 2013-10-28T21:23:40.153 回答