我希望我的Winform在运行时不断检查数据库条目的变化

时间:2014-01-25 10:50:06

标签: c# winforms visual-studio-2012

我有两个应用程序在运行。一种是将用户的手势/面部/语音识别为输入并在成功认证时更新数据库。另一个是Winform,它将触发对数据库条目的button_click操作。我的问题是WinForms。如何在表单运行时不断检查数据库中的新条目?

1 个答案:

答案 0 :(得分:0)

您应该创建一个单独的线程/任务,定期检查数据库。

使用Thread实例的示例(在ConsoleApplication上,但您可以轻松地将其移动到WinForms):

class Program
{
    public static void CheckSomethingInDb()
    {
        while (true)
        {
            // do periodical check 
            Console.WriteLine("Periodical check"); 
            Thread.Sleep(500); 
        }
    }

    static void Main(string[] args)
    {
        var dbCheckerThread = new Thread(CheckSomethingInDb);
        dbCheckerThread.IsBackground = true;
        dbCheckerThread.Start();
        Console.WriteLine("... the application is running further..."); 
        Console.ReadKey();
    }
}

使用Task非常相似:

    static void Main(string[] args)
    {
        Task dbCheckerThread = new Task(CheckSomethingInDb);
        dbCheckerThread.Start();
        Console.WriteLine("... the application is running further..."); 
        Console.ReadKey();
    }

虽然通常建议的做法是将用户应用程序(在您的WinForms应用程序中)与执行某些定期检查/集成/同步的代理分开。因此,最好是单独运行Windows服务或其他一些与主应用程序分开运行的简单应用程序。