gpt4 book ai didi

c# - 异步函数中的 TaskCompletionSource

转载 作者:太空狗 更新时间:2023-10-29 20:54:04 25 4
gpt4 key购买 nike

我有这样一个功能:

public async Task<bool> DoSomething()
{
var tcs = new TaskCompletionSource<bool>();

// Here is the problem. I need to keep this line because I wait on something asynchronously, but the function must return bool and I can't just return tcs.Task
while(something)
await Task.Delay(100);

someobject.somevent += () => {
// do some sht
tcs.SetResult(true);
}

// it doesn't work
return tcs.Task;
}

这只是一个假代码,但我在真实情况下需要它。我想让 DoSomething 保持异步,但我也想在其中保留 Task.Delay/Sleep。我如何在仅返回任务的非异步函数中执行此操作?

更新:

这有效:

class Program
{
static TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();


static Task<bool> Test()
{
// tcs = new TaskCompletionSource<bool>();
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);

}
}

这不是

static async Task<bool> Test()
{
// tcs = new TaskCompletionSource<bool>();
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;
}

更糟糕的是,我已经在我的 Windows 窗体应用程序中测试了它并等待 tcs.Task 导致来自 System.Threading....dll 的奇怪崩溃

最佳答案

如果我理解正确(这很棘手,因为你的问题不是那么容易理解)你可以重述如下:

public async Task<bool> DoSomething()
{
var tcs = new TaskCompletionSource<bool>();
someobject.somevent += () => {
// do some sht
tcs.SetResult(true);
}

return await tcs.Task;
}

关于c# - 异步函数中的 TaskCompletionSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35158546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com