locked
donet core 3 worker service with ZMQ RRS feed

  • Question

  • User718448626 posted

    How do I make the ExecuteAsync wait ?

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
       {
    	 ZmqListener.TransactionReceived += (sender, eventArgs) =>
    	 {
    		// Do Work Here
    	 }
    	 
    	  while (!stoppingToken.IsCancellationRequested)
          {
               var tokenSource = ZmqListener.Listen("tcp://192.160.0.1:5556", "Transaction");
         }
    
    }
    
    public static class ZmqListener
      {
        public static event EventHandler<TransactionReceivedEventArgs> TransactionReceived;
    	
        public static CancellationTokenSource Listen(string uri, string messageType)
        {
          var source = new CancellationTokenSource();
          var token = source.Token;
    
          Task.Factory.StartNew(
            () =>
              {
                using (var socket = new SubscriberSocket())
                {
                  socket.Connect(uri);
                  socket.Subscribe(messageType);
    
                  while (!token.IsCancellationRequested)
                  {
                    HandleMessage(socket.ReceiveFrameString());
                  }
                }
              },
            token);
    
          return source;
        }
    	
    	 private static void HandleMessage(string message)
        {
          var splitMessage = message.Split(' ');
          // Do work here
    	  TransactionReceived?.Invoke(sourceName, new TransactionReceivedEventArgs(message));
    	}
    	
    }

    Thursday, August 29, 2019 10:53 AM

All replies

  • User711641945 posted

    Hi Albertk89,

    Actually i do not know what is your scenario clearly.If you want to make the ExecuteAsync wait,you could use await like below:

     ZmqListener.TransactionReceived += async (sender, eventArgs) =>
     {
          await ZmqListener.YourMethod();
     };

    And make sure that your method should be modified by async Task:

    public async Task YourMethod()
    {
         //your logic
    }

    Best Regatds,

    Rena

    Friday, August 30, 2019 8:42 AM
  • User718448626 posted

    I have remove the while loop in the ExecuteAync and it seems to work.  May I ask, is this the correct approach?  Thank you.

    Saturday, August 31, 2019 12:31 AM
  • User711641945 posted

    Hi Albertk89,

    Albertk89

    I have remove the while loop in the ExecuteAync and it seems to work.  May I ask, is this the correct approach? 

    You have not provide the whole code,so I cannot test the code and answer you whether it is correct or not.I suggest that you could set breakpoint to debug your source code.

    Best Regards,

    Rena

    Monday, September 2, 2019 9:30 AM