2016-11-11 18 views
0

break想我async方法中得到事件循環只執行一次for loop,但是從事件中心得到的事件不斷被一次又一次地調用方法。如何ASYN方法,不斷地從eventhub

我想執行循環只有一次,當得到data == "mytestdata"

如果它的真實發送通知郵件,並且需要打破,因爲我不想再發送郵件,因爲我已經發送了它。

我也嘗試過使用isMailSend = true;,但它執行雙向。

bool isMailSend = false; 
async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages) 
     { 
      foreach (EventData eventData in messages) 
      { 
       string data = Encoding.UTF8.GetString(eventData.GetBytes()); 


       if (data == "mytestdata") 
       { 
        //send mail notification 
       isMailSend = true; 
       Console.WriteLine("mail send "); 
       break; 
       } 

       Console.WriteLine(string.Format("Message received. Partition: '{0}', Data: '{1}'", 
        context.Lease.PartitionId, data)); 
      } 

      //Call checkpoint every 1 minutes, so that worker can resume processing from 1 minutes back if it restarts. 
      if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(1)) 
      { 
       await context.CheckpointAsync(); 
       this.checkpointStopWatch.Restart(); 
      } 
     } 

回答

1

當你ProcessEventsAsync遇到的await,控制返還給調用者,看是否來電還是可以做一些事情,直到來電者遇到的await,此後控制在調用堆棧上升,看是否來電者有事可做,等等。

所以你的線程看到了等待。調用堆棧中的一個調用者不在等待,並調用ProcessEventsAsync。雖然您已經設置了isMailSent,但您不檢查它,因此您的foreach外觀是第二次輸入的。

如下更改代碼:

class MyClass 
{ 

    private bool isMailSent = false; 

    async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages) 
    { 
     if (this.isMailSent) 
     { 
      // do whatever you want to do if a 2nd call is received 
      // while isMailSent 
      ProcessWhileIsMailSent(...) 
     } 
     else 
     { // called for the first time 
      foreach (EventData eventData in messages) 
      { 
       string data = ... 
       if (data == "mytestdata") 
       { 
        this.isMailSent = true; 
       // etc. 

的效果是,雖然isMailSent是真實的,來電者的一​​個決定給你打電話,你的foreach不叫,但(在這個例子中)ProcessWhileIsMailSent (...)

當您準備好再次處理接收到的輸入時,不要忘記將isMailSent設置爲false。

如果您是多線程,請考慮在訪問它之前鎖定isMailSent。