jeudi 15 décembre 2016

Handling Events in method so the value can be picked up when completed in event so it doesn't return null each time

I am trying to figure out the best practice for handling and correctly processing the following: I have an inline method that in the process of the method adds an event handler process, but I need to figure out how to handle the rest of my method to wait until it receives data into that variable before proceeding (or if there is a better practice possibly)

Currently the method I am focused on is an inline method, so it finishes up and tries to return the data from the expected variable before it is assigned to it, so it returns 'null' because it is trying to return it before that event handler gets data to it.

Please let me know what the best practice / patterns are to handle / accomplish this.

Thank you.

[Code Sample] The method I am calling and which is finishing and trying to return the 'recievedMsg' variable value before it is assigned...

    public T Recieve<T>(string routingKey)
    {
        T recievedMsg = default(T);

        try
        {
            _channel.QueueDeclare(queue: routingKey,
                                    durable: false,
                                    exclusive: false,
                                    autoDelete: false,
                                    arguments: null);

            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);

                recievedMsg = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(message);
            };

            _channel.BasicConsume(queue: routingKey,
                                    noAck: true,
                                    consumer: consumer);


        }
        catch (Exception ex)
        {
            // Error Handling
        }

        return recievedMsg;
    }

[Call that is invoking the Method]

        var obj = new testObj()
        {
            Id = 123,
            Name = "Test McTesting",
            Dexcription = "Employee of the Month"
        };


        using (var rbt= new proxyClass("localhost"))
        {
           // .Recieve() method is completing too quickly so always returns null to employee 
           var employee = rbt.Recieve<testObj>("Test McTesting");
        }

Aucun commentaire:

Enregistrer un commentaire