-2

I have the following structure:

 //function called from Node.js
 public Task<object> NodeCall (IDictionary<string, object> payload) {
     Func<object, Task<object>> changed = (Func<object, Task<object>>) payload["changed"];

     return Task.Run (async () => await OnQuery (payload["request"], changed));
 }

public async Task<object> OnQuery (dynamic request, dynamic payload = null) {
    var result = new QueryCallback ();
    //...code...
    return result
}

In the code of "OnQuery" I should call a function of a singleton class and I need to queue the calls. The problem is that queuing I can't handle the thread response and awaiting the result the task send the reply.

My final result would be: put the task in the queue and when the singleton dequeue my task and finish the target function I return the result. In the while the OnQuery task should wait without returning anything.

Can someone help me with that?

Thanks

Edit 1 Servy signed as possible duplicate of this answer but I am not sure it can handle the result... If is it the right way can someone make a better sample please? It's not clear for me

mene
  • 372
  • 3
  • 17
  • Which calls do you need to queue exactly? – MindSwipe May 17 '19 at 13:32
  • @MindSwipe What do u mean? OnQuery Task should be in the queue awaiting it will be removed from queue and executed and only next return the result. But I also consider others approachs – mene May 17 '19 at 13:36

1 Answers1

-1

You can use SemaphoreSlim as noted in the duplicate:

private readonly SemaphoreSlim _mutex = new SemaphoreSlim(1);
public async Task<object> OnQuery (dynamic request, dynamic payload = null)
{
  await _mutex.WaitAsync();
  try
  {
    var result = new QueryCallback ();
    //...code...
    return result
  }
  finally
  {
    _mutex.Release();
  }
}

Side note: this is not technically a queue, since strict FIFO order isn't guaranteed. It is, however, a way to enforce exclusive access to a shared resource, and this should suffice for what you need.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810