I am trying to write a C# method that returns a task. The task should register to an event on another object (that I did not write and do not control) and complete when the event is triggered. The event args contain the result of the task.
I have tried the following idea (which is bad...):
public Task<int> GetValue(ObjectToWaitFor waitFor)
{
var flag = false;
int value = -1;
return Task.Factory.StartNew<int>(() =>
{
waitFor.TheEvent += (s, e) =>
{
value = e.Value;
flag = true;
};
while (!flag)
{
Task.Delay(100).Wait();
}
return value;
});
}
using a flag, which is set to true on the event handler, and then have the task loop until the flag is set to true. But it does not seem like an elegant solution and I wonder if there is some better way.
I suspect you're looking for TaskCompletionSource<TResult>
. Basically, you create one of those (and remember it), and hand back the task that it provides in the Task
property.
When the event is triggered, set the appropriate result/fault on the completion source, and you're done.
See more on this question at Stackoverflow