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 .