DispatcherTimer没有在"发布"模式

时间:2015-01-05 05:28:05

标签: c# asp.net wpf

我们在WPF中开发了一个应用程序。应该在特定的时间间隔刷新此应用程序,因此我们使用了" DispatchTimer"控制。

以下代码用于执行此刷新过程。

 private void PageReferesh()
    {
        try
        {

            DispatcherTimer dispatcherTimer = App.dirctedWorkTaskTimer;
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
            dispatcherTimer.Start();
        }
        catch (Exception ex)
        {

            // throw new Exception(ex.Message, ex);
        }
    }
    protected void dispatcherTimer_Tick(object sender, EventArgs e)
    {

        GetOperatorDetails();
        GetCustomers();

    }

它在开发环境中运行良好。当我们改为"发布模式"并部署到同一系统上的另一个文件夹,它不起作用。

实际上,这同样适用于"发布"模式,从VS2012 IDE运行。复制"发布"它不起作用文件夹(bin / release)到其他文件路径。

1 个答案:

答案 0 :(得分:0)

我相信您拥有的DispatcherTimer不会在主UI调度程序上运行。
如果不是在创建DispatcherPriority实例时设置的ApplicationIdle(它不应该是DispatcherTimer)是什么? 基于此,如果Timer在具有较低优先级的主UI调度程序上运行,则可能无法按预期运行完成,具体取决于可能在UI调度程序的泵栈中排列的其他更高优先级操作。

我建议如下

        Dispatcher _uiRefreshDispatcher;
        //Make sure calling thread is UI thread
        Dispatcher _uiDispatcher = Dispatcher.CurrentDispatcher;

    private void PageRefresh()
    {
        var waitForRefreshWatchThread = new ManualResetEventSlim(false);

        var messageThread = new Thread(() =>
        {
            _uiRefreshDispatcher = Dispatcher.CurrentDispatcher;
            waitForRefreshWatchThread.Set();
            Dispatcher.Run();
            waitForRefreshWatchThread.Dispose();
        }) { Name = "RefresherThread", IsBackground = true };
        messageThread.SetApartmentState(ApartmentState.STA);
        messageThread.Start();

        waitForRefreshWatchThread.Wait();

        var refreshTimer = new DispatcherTimer(DispatcherPriority.Send, _uiRefreshDispatcher);
        refreshTimer.Tick += OnRefreshTimeElapsed;
        refreshTimer.Interval = TimeSpan.FromSeconds(10);
    }

    private void OnRefreshTimeElapsed(object sender, EventArgs e)
    {
        if (!_uiDispatcher.CheckAccess())
        {
            _uiDispatcher.BeginInvoke((Action<object, EventArgs>)OnRefreshTimeElapsed, sender, e);
        }
        else
        {
            //Update UI here
        }
    }