开发者

Creating a non blocking async gate in C#

开发者 https://www.devze.com 2023-02-03 12:35 出处:网络
I need to create a gate to a resource in an async programming model so that one and only one thread can have access to a resource at any given time. Given the async programming model I would like the

I need to create a gate to a resource in an async programming model so that one and only one thread can have access to a resource at any given time. Given the async programming model I would like the remaining requests to the resource to be queued so that I don't blok threads while waiting for the resource to become available.

I've looked and found a reader/writer gate in Jeffrey Richter's power threading library however I'm searching for something a bit different.

I have a vague idea that I would like the signature of the gate class to look like this:

public class Gate
{
  public IAsyncResult BeginEnterGate(AsyncCallback callback, object state)
  {
    ...
  }

  public GateRequest EndEnterGate(IAsyncResult result)
  {
    return ...;
  }
}

The returned gate request should be IDisposable and when disposed the gate would allow the next thread to use the resource.

public class GateRequest : IDisposable
{
  public void Dispose()
  {
    /* release gate */
  }
}

By having this I can utilize Jefrey Ricters powerthreading libary like so:

public IAsyncResult BeginFoo(string bar, AsyncCallback callback, object state)
{
  AsyncEnumerator ae = new AsyncEnumerator();
  return ae.BeginExecute(DoFoo(ae, bar), callback, state);
}

public void EndFoo(IAsyncResult result)
{
  AsyncEnumerator.FromAsyncResult(result).EndExecute(result);
}

private IEnumerator<int> DoFoo(AsyncEnumerator ae, string bar)
{
  gate.BeginEnterGate(ae.End(), null);
  yield return 1;
  var gateReleaser = gate.En开发者_JAVA技巧dEnterGate(ae.DequeueAsyncResult());

  using (gateReleaser)
  {
    /* do work related to the resource */
  }
}

I might be staring myself blind at a certain way to solve this, so I'm also open to other suggestions.


My Power Threading Library has a SyncGate class that integrates in with the AsyncEnumerator. I think it provides the API you desire.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号