首页 > 解决方案 > c# 每 x 秒运行一次数据库任务

问题描述

我想运行一个任务来查询数据库以获取用户的新消息。我希望任务每隔 x 秒运行一次,以新的方式运行,这样它就不会导致 UI 变得无响应。
如果数据库任务找到消息,那么我希望它使这些消息可用于 UI。

我认为整个循环会在它自己的线程中运行,而不是在 UI 线程中有一个循环,它会每隔 x 秒创建一个新线程。我认为这会停止对数据库的多次调用,例如,如果我将查找设置为每 5 秒一次并且数据库需要超过 5 秒的时间来响应。我一直在寻找好几个小时 - 我发现的最好的文章是: https ://blogs.msdn.microsoft.com/benwilli/2016/06/30/asynchronous-infinite-loops-instead-of-timers/

我是线程新手,上面的链接在其最后一个示例 DoWorkAsyncInfiniteLoop 中似乎相对简单,但它似乎在 UI 线程上运行(尽管它提到您可以使用 Task.Run 使其在自己的线程中运行,并且我'不确定 UI 线程如何使用找到的消息。

任何建议将不胜感激!

标签: c#multithreadingtimer

解决方案


好的有一些小困难 - 不能使用调度程序,因为我正在使用 MVVM 并且视图模型没有调度程序,因为它不是从 UI 基础派生的。这是我为其他试图实现这一目标的人提供的最终代码

 public MainViewModel()  //the constructor for the viewmodel
    {
        _Repo = CurrentApp.MainController.RepositoryManager; // this is my database access methods

        Task t = Task.Run(CheckMessagesAsyncInfiniteLoop);  //run the new thread
    }


    private async Task CheckMessagesAsyncInfiniteLoop()  //this is my infinite loop as described in the above link, but run from the above Task.Run
    {
        while (true)
        {
            // Check the messages in the database
             Messages = _Repo.Service_Message_GetList(CurrentApp.CurrentUser.BasicInfo.UserID);

            // pause for the next check
            await Task.Delay(30000);
        }
    }

    Repository.DomainLayer.MessageCollection _Messages;  //the collection that will be updated by the thread above
    public Repository.DomainLayer.MessageCollection Messages  //the property that my view is bound to
    {
        get
        {
            return _Messages;
        }
        set
        {
            _Messages = value;
            NotifyPropertyChanged();
        }
    }

推荐阅读