在winforms Presenter中使用System.Timers.Timer

时间:2013-10-28 20:31:38

标签: c# .net winforms timer

如何在演示者中设置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);

1 个答案:

答案 0 :(得分: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);                
}