StackOverflower StackOverflower - 8 months ago 27
C# Question

Is this the correct async approach for waiting for a property to be set?

I have a class property that is set by a background operation. This is my method that reads the value for that property. The idea is wait a reasonable amount of time before returning null since that means there is still work in progress about to complete

public async Task<Entity> GetEntityAsync()
int tries = 0;
while (_entity == null && tries < 2)
await Task.Delay(100);

return _entity;

Then I use it like this

var entity = await entityManager.GetEntityAsync();

Is this approach correct or there is any better option?


The background operation that sets
is a third party component that reports trough an event that data is available. I want to translate the event approach to an async/await method. Reasons for this are

  • This method is used on many places (I'm doing a refactoring) and it's not prepared for an event oriented approach.

  • Event oriented approach is more complex to implement. I just want to make sure I don't hang the main thread, 99% of the times,
    will have a value different to null on first shoot.


You said that your data source uses an event to return the _entity. Events are quite easily wired into a TaskCompletionSource. Consider:

public Task<Data> GetDataAsync()
  var tcs = new TaskCompletionSource<Data>();

  dataSource.DataReturned += d => tcs.SetResult(d);

  return tcs.Task;

Now you have a nice little asynchronous method wired to your data sources event.

Of course, this is just a very simple example that makes a lot of assumptions, no error handling etc., but it should put you on the way to a good solution. No need for polling if you have events :)