-1

I have below code which will run for infinite time period but I'm going to take time as input from user.

So if user enter 15mits I want to run this code for 15 mits.

Yes I can compare the DateTime.Now with 15mits but is there any other efficient way to do so ? As this will be my multi threading application.

private static async void SendDeviceToCloudMessagesAsync(string deviceid , string deviceKey)
        {
            deviceClient = DeviceClient.Create("HOSTNAME", new DeviceAuthenticationWithRegistrySymmetricKey(deviceid, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);

            double minTemperature = 20;
            double minHumidity = 60;
            int messageId = 1;
            Random rand = new Random();
            do
            {
                double currentTemperature = minTemperature + rand.NextDouble() * 15;
                double currentHumidity = minHumidity + rand.NextDouble() * 20;
                var telemetryDataPoint = new
                {
                    messageId = messageId++,
                    deviceId = deviceid,
                    temperature = currentTemperature,
                    humidity = currentHumidity
                };
                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString));
                message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");
                await deviceClient.SendEventAsync(message);
                Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
                await Task.Delay(1000);
            } while (true);
        }
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 1
    What do you mean by "this will be my multi threading application". Is this Method running parallel to your main Application or? – MindSwipe Oct 23 '18 at 06:04
  • Possible duplicate of [How to execute the loop for specific time](https://stackoverflow.com/questions/5945533/how-to-execute-the-loop-for-specific-time) – Gauravsa Oct 23 '18 at 06:38
  • Possible duplicate https://stackoverflow.com/questions/5945533/how-to-execute-the-loop-for-specific-time – Gauravsa Oct 23 '18 at 06:39
  • [Cancel async tasks after a period of time (C#).](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time) Downvote reason: Lack of research. You are expected search the official documentation before posting a question, especially since you have 5k reputation you should know that by now. – Zohar Peled Oct 23 '18 at 06:50

2 Answers2

1

You could check out System.Timers.Timer. You create an instance of it setting the interval in the constructor, then write a method to handle the Elapsed event.

    // Create a timer with a two second interval.
    var aTimer = new System.Timers.Timer(2000);
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent // Name this whatever you want and put code here;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;

All you have to do now is write the Elapsed event handler... OnTimedEvent in this case. Note that this method must have this signature:

private static void Object source, ElapsedEventArgs e)

0

try to replace your code against

await Task.Delay(TimeSpan.FromSeconds(1000));

Jones
  • 141
  • 1
  • 9