2017-03-09 44 views
0

我有一段代码使用rabbitMQ来管理一段时间内的作业列表。 因此,我有一个连接和一个开放给RabbitMQ服务器来处理这些作业的通道。我排队的工作有以下:RabbitMQ客户端(DotNet Core)阻止应用程序关闭

public override void QueueJob(string qid, string jobId) { 
     this.VerifyReadyToGo(); 

     this.CreateQueue(qid); 
     byte[] messageBody = Encoding.UTF8.GetBytes(jobId); 
     this.channel.BasicPublish(
      exchange: Exchange, 
      routingKey: qid, 
      body: messageBody, 
      basicProperties: null 
     ); 
     OLog.Debug($"Queued job {jobId} on {qid}"); 
    } 

    public override string RetrieveJobID(string qid) { 
     this.VerifyReadyToGo(); 

     this.CreateQueue(qid); 

     BasicGetResult data = this.channel.BasicGet(qid, false); 
     string jobData = Encoding.UTF8.GetString(data.Body); 

     int addCount = 0; 
     while (!this.jobWaitingAck.TryAdd(jobData, data.DeliveryTag)) { 
      // try again. 
      Thread.Sleep(10); 
      if (addCount++ > 2) { 
       throw new JobReceptionException("Failed to add job to waiting ack list."); 
      } 
     } 
     OLog.Debug($"Found job {jobData} on queue {qid} with ackId {data.DeliveryTag}"); 
     return jobData; 
    } 

的问题是,经过这样的任何方法调用(发布,获取,或确认)创建某种后台线程时,通道和连接关闭时不关闭。 这意味着测试通过并且操作成功完成,但是当应用程序尝试关闭它时会挂起并且不会完成。

这里是参考

public override void Connect() { 
     if (this.Connected) { 
      return; 
     } 
     this.factory = new ConnectionFactory { 
      HostName = this.config.Hostname, 
      Password = this.config.Password, 
      UserName = this.config.Username, 
      Port = this.config.Port, 
      VirtualHost = VirtualHost 
     }; 
     this.connection = this.factory.CreateConnection(); 
     this.channel = this.connection.CreateModel(); 
     this.channel.ExchangeDeclare(
      exchange: Exchange, 
      type: "direct", 
      durable: true 
     ); 
    } 

我能做些什么来解决这个问题(RabbitMQ的客户端应用程序防止从退出)的连接方法?

回答

0

我不知道为什么,但这种变化的连接方法使区别:

public override void Connect() { 
     if (this.Connected) { 
      return; 
     } 
     this.factory = new ConnectionFactory { 
      HostName = this.config.Hostname, 
      Password = this.config.Password, 
      UserName = this.config.Username, 
      Port = this.config.Port, 
      UseBackgroundThreadsForIO = true 
     }; 
     this.connection = this.factory.CreateConnection(); 
     this.channel = this.connection.CreateModel(); 
     this.channel.ExchangeDeclare(
      exchange: Exchange, 
      type: "direct", 
      durable: true 
     ); 
    } 
+0

[“后台线程不守管理的执行环境中运行”(https://msdn.microsoft .com/en-us/library/h339syd0(v = vs.110).aspx)。不要太猜测这就是你的“UseBackgroundThreadsForIO”改变正在做的事情;) – Tung

相关问题