Home > Blockchain >  How to access variable from the while loop in the function to the outside the function in C#?
How to access variable from the while loop in the function to the outside the function in C#?

Time:07-28

I am sending telemetry(data) from simulator device to Azure IoT Hub and receiving that telemetry into this code.

 namespace CentralSystem
{
  internal class Program
  {
    static readonly string connectionString = "IoT Hub Connection string here";
    static readonly string iotHubD2cEndpoint = "messages/events";
    static EventHubClient eventHubClient;

    public static Dictionary<string, string> values = new Dictionary<string, string>();

    private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)   
    {
        var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
        while (true)
        {
            if (ct.IsCancellationRequested) break;

            EventData eventData = await eventHubReceiver.ReceiveAsync();
            if (eventData == null) continue;

            string data = Encoding.UTF8.GetString(eventData.GetBytes());
            values = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);  
            foreach (var kv in values)                                                 
            {                                                                          
                Console.WriteLine(kv.Key   " : "   kv.Value);                          
            }                                                                          
            Console.WriteLine();
        }
    }

This above code run perfectly but I need to access "data" variable outside the function means access it globally. Because I need to put all values in "data" variable to dictionary. so that I have declared dictionary as globally.

Please tell me that how to figure out this thing?

CodePudding user response:

if I understood correctly. Isn't it stored in your "values" dictionary?

If you need only values: Create List of strings above the function (like your values):

List<string> listOfValues = new List<string>()

and do this like a dictionary but only for Values:

listOfValues.Add(Value)

After the function, do what you want with it

CodePudding user response:

Looking at the code you have provided you are already storing all values of the "data" variable in the dictionary "values" which is globally declared. You can directly use "values" to proceed further and access the data inside it.

  • Related