Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# wcf msmq侦听器服务删除消息,但不删除';t过程_C#_Wcf_Service_Listener_Msmq - Fatal编程技术网

C# wcf msmq侦听器服务删除消息,但不删除';t过程

C# wcf msmq侦听器服务删除消息,但不删除';t过程,c#,wcf,service,listener,msmq,C#,Wcf,Service,Listener,Msmq,我有一个WCF服务,可以在MSMQ中创建私有消息。消息创建得很好,我可以看到客户端应用程序正在创建的消息 我还有一个MSMQ侦听器服务,它似乎运行良好。当我启动服务时,它似乎成功地“处理”了队列中的消息,并将其删除。但是,我的侦听器服务的实现似乎没有得到执行 我对MSMQ相当陌生,我不知道为什么要从队列中删除消息,以及为什么侦听器方法中的代码没有得到执行 下面是我的服务课程 [ServiceContract(Namespace = ServiceConstants.NAMESPACE, Name

我有一个WCF服务,可以在MSMQ中创建私有消息。消息创建得很好,我可以看到客户端应用程序正在创建的消息

我还有一个MSMQ侦听器服务,它似乎运行良好。当我启动服务时,它似乎成功地“处理”了队列中的消息,并将其删除。但是,我的侦听器服务的实现似乎没有得到执行

我对MSMQ相当陌生,我不知道为什么要从队列中删除消息,以及为什么侦听器方法中的代码没有得到执行

下面是我的服务课程

[ServiceContract(Namespace = ServiceConstants.NAMESPACE, Name = "IOrderService")]
public interface IOrderQueueProcessingService
{

    [OperationContract(IsOneWay = true, Action = "*")]
    void ProcessOrderQueue(MsmqMessage<string> message);

}

public abstract class OrderQueueProcessingServiceBase : ServiceBase, IOrderQueueProcessingService
{
    #region CONSTRUCTORS

    protected OrderQueueProcessingServiceBase() { }

    protected OrderQueueProcessingServiceBase(List<EventRecord> existingList) : base(existingList) { }

    #endregion //CONSTRUCTORS

    #region IOrderQueueProcessingService Members


    [OperationBehavior(TransactionScopeRequired = false, TransactionAutoComplete = true)]
    public virtual void ProcessOrderQueue(MsmqMessage<string> message)
    {
        throw new NotImplementedException();
    }

    #endregion
}

public class OrderQueueProcessingService : OrderQueueProcessingServiceBase
{
    #region Constructors


    public OrderQueueProcessingService() {}

    public OrderQueueProcessingService(List<EventRecord> existingList) : base(existingList) { }


    #endregion

    /// <summary>
    ///     Processes any Orders in the Orders Queue
    /// </summary>
    /// <param name="message"></param>
    public override void ProcessOrderQueue(MsmqMessage<string> message)
    {

        var q = new MessageQueue(@".\private$\msmqdemo/submitorderservice.svc");
        q.Send("hey");
        /*
        using (new Tracer("OrderQueueProcessingService"))
        {
            // add data context to work with.
            using (var unitOfWork = new TLFDataContext())
            {

                var newOrderLines = new List<OrderLineDataContract>
                                {
                                    new OrderLineDataContract
                                        {
                                            C = "test",
                                            IC = "msw",
                                            Qty = 1,
                                            T = "volume" ,
                                            ED = DateTime.UtcNow.AddDays(5)
                                        }
                                };

                var newOrder = new OrderDataContract
                {
                    LIs = newOrderLines.AsEnumerable(),
                    PId = 9323,
                    POId = 8686,
                    S = "new"

                };
                var orderService = new OrderService();
                var createdOrder = orderService.CreateOrder(null, null, newOrder);
                //unitOfWork.SubmitUnitOfWork();

                //return null;
            }
        }*/


    }

}
[ServiceContract(Namespace=serviceconts.Namespace,Name=“IOrderService”)]
公共接口IOrderQueueProcessingService
{
[运营合同(IsOneWay=true,Action=“*”)]
无效ProcessOrderQueue(MsmqMessage消息);
}
公共抽象类OrderQueueProcessingServiceBase:ServiceBase,IOrderQueueProcessingService
{
#区域构造函数
受保护的OrderQueueProcessingServiceBase(){}
受保护的OrderQueueProcessingServiceBase(列表existingList):base(existingList){}
#endregion//构造函数
#区域IOrderQueueProcessingService成员
[操作行为(TransactionScopeRequired=false,TransactionAutoComplete=true)]
公共虚拟无效ProcessOrderQueue(MsmqMessage消息)
{
抛出新的NotImplementedException();
}
#端区
}
公共类OrderQueueProcessingService:OrderQueueProcessingServiceBase
{
#区域构造函数
public OrderQueueProcessingService(){}
public OrderQueueProcessingService(List existingList):基本(existingList){}
#端区
/// 
///处理订单队列中的任何订单
/// 
/// 
公共覆盖无效ProcessOrderQueue(MsmqMessage消息)
{
var q=new MessageQueue(@“.\private$\msmqdemo/submitorderservice.svc”);
q、 发送(“嘿”);
/*
使用(新跟踪程序(“OrderQueueProcessingService”))
{
//添加要使用的数据上下文。
使用(var unitOfWork=new TLFDataContext())
{
var newOrderLines=新列表
{
新OrderLineDataContract
{
C=“测试”,
IC=“msw”,
数量=1,
T=“音量”,
ED=DateTime.UtcNow.AddDays(5)
}
};
var newOrder=neworderdatacontract
{
LIs=newOrderLines.AsEnumerable(),
PId=9323,
POId=8686,
S=“新”
};
var orderService=new orderService();
var createdOrder=orderService.CreateOrder(null,null,newOrder);
//unitOfWork.SubmitionTofWork();
//返回null;
}
}*/
}
}
我注释掉了我最终尝试执行的代码,并将其替换为一个简单的MSMQ消息发送,用于测试。这看起来应该很好用。任何帮助都将不胜感激

下面的配置设置

<service name="ServiceImplementation.OrderQueueProcessingService">
    <host>
      <baseAddresses>
        <add baseAddress="https://localhost:9000/OrderQueueProcessingService.svc" />
      </baseAddresses>
    </host>
    <endpoint address="net.msmq://localhost/private/testingqueue/OrderQueueProcessingService.svc" binding="netMsmqBinding" bindingConfiguration="MsmqBindingNonTransactionalNoSecurity" contract="IOrderQueueProcessingService" />
  </service>

我能够解决我的问题。我没有QueueOnPeekComplted事件的任何事件处理。我将其添加到一个Initialize方法中,并成功地处理了我的消息。我还添加了对无法处理的消息的处理。下面是我的OrderQueueProcessingService的新实现

public class OrderQueueProcessingService : OrderQueueProcessingServiceBase, IDisposable
{
    #region Constructors

    public OrderQueueProcessingService()
    {
        Initialize(ConfigurationManager.AppSettings["OrderQueueProcessingQueueName"]);
    }

    public OrderQueueProcessingService(List<EventRecord> existingList) : base(existingList) {}

    #endregion

    #region Properties

    private MessageQueue Queue { get; set; }

    #endregion

    #region IDisposable Members

    public new void Dispose()
    {
        if (Queue == null) return;

        //unsubscribe and dispose
        Queue.PeekCompleted -= QueueOnPeekCompleted;
        Queue.Dispose();
    }

    #endregion

    private void Initialize(string queueName)
    {
        Queue = new MessageQueue(queueName, false, true, QueueAccessMode.Receive)
                    {
                            Formatter = new XmlMessageFormatter(new[] {typeof (OrderQueueDataContract)})
                    };

        //setup events and start.
        Queue.PeekCompleted += QueueOnPeekCompleted;
        Queue.BeginPeek();
    }

    private static void MoveMessageToDeadLetter(IDisposable message)
    {
        var q = new MessageQueue(ConfigurationManager.AppSettings["OrderProcessingDLQ"], QueueAccessMode.Send)
                    {
                            Formatter = new XmlMessageFormatter(new[] {typeof (OrderQueueDataContract)})
                    };
        q.Send(message, MessageQueueTransactionType.Single);
        q.Dispose();
    }

    /// <summary>
    ///     Processes the specified Order message
    /// </summary>
    /// <param name="orderMessage"></param>
    public override void ProcessOrderQueue(OrderQueueDataContract orderMessage)
    {
        using (var unitOfWork = new MyDataContext())
        {
            switch (orderMessage.M.ToLower())
            {
                case "create":
                    DataAccessLayer.CreateOrder(unitOfWork, orderMessage.O.TranslateToBe());
                    break;
                default:
                    break;
            }
        }
    }

    private void QueueOnPeekCompleted(object sender, PeekCompletedEventArgs peekCompletedEventArgs)
    {
        var asyncQueue = (MessageQueue) sender;

        using (var transaction = new MessageQueueTransaction())
        {
            transaction.Begin();
            try
            {
                using (var message = asyncQueue.ReceiveById(peekCompletedEventArgs.Message.Id, TimeSpan.FromSeconds(30), transaction))
                {
                    if (message != null) ProcessOrderQueue((OrderQueueDataContract) message.Body);
                }
            }
            catch (InvalidOperationException ex)
            {
                transaction.Abort();
            }
            catch (Exception ex)
            {
                transaction.Abort();
            }

            if (transaction.Status != MessageQueueTransactionStatus.Aborted) transaction.Commit();
            else
            {
                using (var message = asyncQueue.ReceiveById(peekCompletedEventArgs.Message.Id, TimeSpan.FromSeconds(30), transaction))
                {
                    if (message != null)
                    {
                        MoveMessageToDeadLetter(message);
                        message.Dispose();
                    }
                }

                EventLog.WriteEntry("OrderQueueProcessingService", "Could not process message: " + peekCompletedEventArgs.Message.Id);
            }
            transaction.Dispose();
        }

        asyncQueue.EndPeek(peekCompletedEventArgs.AsyncResult);
        asyncQueue.BeginPeek();
    }
}
公共类OrderQueueProcessingService:OrderQueueProcessingServiceBase,IDisposable { #区域构造函数 public OrderQueueProcessingService() { 初始化(ConfigurationManager.AppSettings[“OrderQueueProcessingQueueName]”); } public OrderQueueProcessingService(List existingList):基本(existingList){} #端区 #区域属性 私有消息队列{get;set;} #端区 #区域IDisposable成员 公开新的无效处置() { if(Queue==null)返回; //取消订阅并处置 Queue.PeekCompleted-=QueueOnPeekCompleted; Queue.Dispose(); } #端区 私有无效初始化(字符串队列名称) { 队列=新消息队列(queueName、false、true、QueueAccessMode.Receive) { Formatter=新的XmlMessageFormatter(新[]{typeof(OrderQueueDataContract)}) }; //设置事件并启动。 Queue.PeekCompleted+=QueueOnPeekCompleted; Queue.BeginPeek(); } 私有静态无效MoveMessageToDeadLetter(IDisposable消息) { var q=新消息队列(ConfigurationManager.AppSettings[“OrderProcessingDLQ”],QueueAccessMode.Send) { Formatter=新的XmlMessageFormatter(新[]{typeof(OrderQueueDataContract)}) }; q、 发送(message,MessageQueueTransactionType.Single); q、 处置(); } /// ///处理指定的订单消息 /// /// 公共覆盖无效ProcessOrderQueue(OrderQueueDataContract orderMessage) { 使用(var unitOfWork=new MyDataContext()) { 开关(orderMessage.M.ToLower()) { 案例“创建”: DataAccessLayer.CreateOrder(unitOfWork,orderMessage.O.TranslateToBe()); 打破 违约: 打破 } } } private void QueueOnPeekCompleted(对象发送方,PeekCompletedEventArgs