How to notify a windows service(c#) of a DB Table Change(sql 2005)?

前端 未结 5 1735
悲&欢浪女
悲&欢浪女 2020-12-08 05:29

I have a table with a heavy load(many inserts/updates/deletes) in a SQL2005 database. I\'d like to do some post processing for all these changes in as close to real time as

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 05:58

    In similar circumstances we are using CLR trigger that is writing messages to the queue (MSMQ). Service written in C# is monitoring the queue and doing post-processing. In our case it is all done on the same server, but you can send those messages directly to the remote queue, on a different machine, totally bypassing "local listener".

    The code called from trigger looks like this:

    public static void SendMsmqMessage(string queueName, string data)
    {
        //Define the queue path based on the input parameter.
        string QueuePath = String.Format(".\\private$\\{0}", queueName);
    
        try
        {
            if (!MessageQueue.Exists(QueuePath))
                MessageQueue.Create(QueuePath);
    
            //Open the queue with the Send access mode
            MessageQueue MSMQueue = new MessageQueue(QueuePath, QueueAccessMode.Send);
    
            //Define the queue message formatting and create message
            BinaryMessageFormatter MessageFormatter = new BinaryMessageFormatter();
            Message MSMQMessage = new Message(data, MessageFormatter);
    
            MSMQueue.Send(MSMQMessage);
        }
        catch (Exception x)
        {
            // async logging: gotta return from the trigger ASAP
            System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(LogException), x);
        }
    }
    

提交回复
热议问题