I have a function like this:
public async Task<bool> DoSomething()
{
var tcs = new TaskCompletionSource<bool>();
while(something)
await Task.Delay(100);
someobject.somevent += () => {
tcs.SetResult(true);
}
return tcs.Task;
}
This is just fake code, but I have a real situation when I need it. I want to keep DoSomething asynchronous, but I also want to keep Task.Delay / Sleep in it. How to do this in a not-async function that returns only a task?
UPDATE:
THIS WORK:
class Program
{
static TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
static Task<bool> Test()
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("Waiting...");
Thread.Sleep(5000);
Console.WriteLine("Setting result");
if(tcs.TrySetResult(true))
Console.WriteLine("Result has been set");
});
return tcs.Task;
}
static async Task Test2()
{
Console.WriteLine("Starting awaiting");
var result = await Test();
Console.WriteLine(result.ToString());
}
static void Main(string[] args)
{
Test2();
Console.ReadKey(false);
}
}
and it is not
static async Task<bool> Test()
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("Waiting...");
Thread.Sleep(5000);
Console.WriteLine("Setting result");
if(tcs.TrySetResult(true))
Console.WriteLine("Result has been set");
});
return await tcs.Task;
}
worse, I tested it in my windows forms application and expected tcs.Task caused a weird crash when exiting System.Threading .... dll
source
share