2017-03-09 74 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

相關問題