0

I want to Run my Api Mthod in background and using await task.whenall to long run my method. I want to run this method in background. Now when i run application api call from layout application using javascript and then run Tasks in background using Task.Whenall(task.toArray())

But when i go to perform another process of my application this javascript again call api from layout and add same or duplicate tasks in Task.When all task.array and tasks running duplicate. How can i manage. Here is my code

Api Code

var tasks = new List<Task>();
        IHttpActionResult ret = null;
        eventHubClient = EventHubClient.CreateFromConnectionString(IOTHUBSTRING);
        //deviceEntity = listOfDevices.Find((e) => { return e.Id == "IoT_Device2"; });
        CancellationTokenSource cts = new CancellationTokenSource();
        var runtimeInfo = await eventHubClient.GetRuntimeInformationAsync();
        var d2cPartitions = runtimeInfo.PartitionIds;
        foreach (string partition in d2cPartitions)
        {
            tasks.Add(device_data.ReceiveMessagesFromDeviceAsync(partition, cts, eventHubClient));
        }

        await Task.WhenAll(tasks.ToArray());

Long Running Method

public static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationTokenSource ct, EventHubClient eventHubClient)
{
    EventHubConsumerGroup group = eventHubClient.GetDefaultConsumerGroup();
    var eventHubReceiver = group.CreateReceiver(partition, EventPosition.FromEnqueuedTime(DateTime.Now));
    Debug.WriteLine("Create receiver on partition: " + partition);
    while (true)
    {
        if (ct.IsCancellationRequested) break;

        Debug.WriteLine("Listening for messages on: " + partition);
        // Check for EventData - this methods times out if there is nothing to retrieve.
        var events = await eventHubReceiver.ReceiveAsync(100, TimeSpan.FromSeconds(10));

        // If there is data in the batch, process it.
        if (events == null) continue;

        foreach (EventData eventData in events)
        {
            string data = Encoding.UTF8.GetString(eventData.GetBytes());
            Debug.WriteLine("Message received on partition {0}:", partition);
            Debug.WriteLine("  {0}:", data);
            Debug.WriteLine("Application properties (set by device):");
            //await eventHubClient.CloseAsync();
        }
    }
}

Javascript code in layout

      <script type="text/javascript">
    $(document).ready(function () {
        var someRootPath = "@Url.Content("~")";
        (function randomGenerator() {
            $.ajax({
        //url: someRootPath + 'TestBlob/GetRandomValue',
      //   //url: "https://localhost:44386/api/DeviceData/getaction",
        //method: 'GET',
                type: "GET",
                url: "/api/signalIR/getData",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
        success: function (data) {
            // $('#pValue').html(data.someValue);
        },
        complete: function () {
            setTimeout(randomGenerator, 1000);
        }
    });
})();
    });
    </script>

I want to Run Task only one time then automatically run in bakcground i dont want to duplicate this task. What should i do please help me .

  • Just a heads up, you could also use Hangfire to schedule jobs on the backend. – sommmen Apr 08 '20 at 09:49
  • You approach is not correct to read data from eventhub, When you have started one task to read data from event hub, What the second task will do? you have single consumer group and you are reading data from all partition. – Pankaj Rawat Apr 08 '20 at 09:59
  • @Panjkaj Rawat Sir guide me what should i do here. which approach is better. I need read Data from all Iot hub devices i have more then 5 Iot Devices and i need to read data from all Iot Devices on real time . Which approach should i use then.. here when on task reading data another task is waiting to complete this its going – Hassan Shabbir Apr 08 '20 at 10:24

0 Answers0