实现事件处理程序C#

时间:2014-02-20 09:08:22

标签: c# .net event-handling

c#应用程序多次在MS SQL数据库表上写入。 必须由另一个c#应用程序读取和处理此表的记录。

目前我已经实现了I Threading计时器,如果表有行并且处理数据,它会查找(每2秒):

System.Threading.Timer checkTimer;

checkTimer = new System.Threading.Timer(Callback, null, 2000, 500);

private void InitSQLCon()
{
    Con = new SqlConnection(ConectionString);
    Con.Open();
}        

private void Callback(Object state)
{
    string queryString = "Select [Wi_Customer ID],[Wi_License_plate_ID] from " + Properties.Settings.Default.Table1 + " where Wi_Car_Rfid='" + s + "'";
    SqlCommand command = new SqlCommand(queryString, Con);

    SqlDataReader reader = command.ExecuteReader();
    if (reader.HasRows)
    {
      ///...make neccessary operations
    }       
}

我的问题是目前的实施效率不高。 使用计时器检查表是非常耗费资源的。 我想以事件驱动的方式做到这一点。 理想情况下,我想实现add record to table1引发的事件处理程序 事件。 如果这可能(因为我从未实现过事件处理程序),我将不胜感激任何有关如何做到这一点的反馈。

1 个答案:

答案 0 :(得分:2)

SQL Server中的一些更改跟踪功能,最值得注意的是通过SqlDependency公开 - 但是,坦率地说,我认为你会更好地看一下单独的通知机制。例如,我是redis pub / sub的忠实粉丝,因为设置起来非常简单(哎呀,专用的pub-sub服务器甚至不需要持久化,所以“bgsave”在Windows上使redis变得棘手的“/”fork“问题不适用,所以你可以使用nuget上可用的redis-server。然后,您只需让您的工作者订阅一个命名通道,并且系统的其他部分在添加工作时会向该命名通道广播一条消息。简单高效。为了获得稳健性,您还需要手动定期轮询 - 但可能是在一个慢得多的轮询中 - 可能每30秒或者其他什么。


以下是通过BookSleeve使用redis的pub / sub示例(您还需要在本地计算机上运行redis-server):

using System;
using System.Text;
using BookSleeve;

static class Program
{
    static void Main()
    {
        // IMPORTANT: the "pub" and "sub" can be on entirely separate machines,
        // as long as they are talking to the same server. They are only shown
        // together here for convenience
        using (var sub = new RedisSubscriberConnection("localhost"))
        using (var pub = new RedisConnection("localhost"))
        {
            sub.Open();
            pub.Open();

            sub.Subscribe("busytime", (queue,payload) =>
            {
                // you don't actually need the payload, probably 
                var received = Encoding.UTF8.GetString(payload);
                Console.WriteLine("Work to do! Look busy!: " + received);
            });

            string line;
            Console.WriteLine("Enter messages to send, or q to quit");
            while((line = Console.ReadLine()) != null && line != "q")
            {
                pub.Publish("busytime", line);
            }
        }
    }
}