I have the following code structure:
private AutoResetEvent _renderCompleteEvent = new AutoResetEvent(false);
// GET: api/<controller>
[HttpGet]
public async Task<string> GetAsync()
{
// Subscribe to the response from Redis publish
_pubsub.Subscribe("x", (channel, message) => RenderComplete(message));
// Ideally I would like to wait on RenderComplete and have it return a string here
// string messageContent = await RenderComplete()..
_renderCompleteEvent.WaitOne();
return messageContent;
}
private void RenderComplete(string json)
{
_renderCompleteEvent.Set();
}
Ideally I would like to be able to wait on a function call which would return when I get a message from Redis and the function would return the message content.
Instead I had to implement it using an AutoResetEvent and I would have to pass the message content back as a global class variable.
Is there a way to achieve what I want here to make the code a bit more elegant?
2
Answers
Yes, you can use a
TaskCompletionSource<T>
to make pretty much anything awaitable:Note that
TaskCompletionSource<T>
can only be completed once; it can’t be “reset”. So you would probably prefer a solution like this that combines the subscribing and message retrieval:You may also want to modify
GetMessageAsync
to handle things like unsubscribing and timing out if there’s no message.i did it and founded this solution to call minio async service in asp.netcore.
your Service in controller
get file list from minio service
asp.netasp.netcoreminioclientlistobjectsasynciobservable