延迟继续,不工作
本文关键字:工作 继续 延迟 | 更新日期: 2023-09-27 18:14:35
我的问题是为什么延迟方法不工作(整个操作不等待4秒),60%没有显示在lable1内部。
更精确地说,操作的顺序应该是这样的,整个操作需要8秒。但是需要4秒,LongTimeMethod1()
里面的Thread.Sleep(4000)
工作
LongTimeMethod1()//delay for 4 sec,show 60%
delay()//delay for 4 sec
LongTimeMethod()//40% imidiatly
我知道我可以用await和async编写代码,但我想知道我在这段代码中做错了什么。
private void button1_Click(object sender, EventArgs e)
{
CallBigMethod();
label1.Text =@"Waiting ...";
}
private async void CallBigMethod()
{
var result = await BigMethod();
label1.Text = result;
}
private Task<string> BigMethod()
{
return Task.Factory
.StartNew(() => LongTimeMethod1())
.ContinueWith((pre) => Delay())
.ContinueWith((pre) => LongTimeMethod());
}
private string LongTimeMethod()
{
return "40%...";
}
public async Task Delay()
{
await Task.Delay(4000);
}
private string LongTimeMethod1()
{
Thread.Sleep(4000);
return "60%...";
}
.ContinueWith((pre) => Delay())
返回的Task
实际上是一个Task<Task>
。该延续将在完成开始延迟后立即结束,但由于延迟是异步的,因此它不会等待延迟完成。您需要打开Task<Task>
,以便向内部任务添加延续,并在延迟完成时让程序继续运行,而不是在启动时完成。
幸运的是,有一个Unwrap
方法可以为我们完成所有这些。
private Task<string> BigMethod()
{
return Task.Factory
.StartNew(() => LongTimeMethod1())
.ContinueWith((pre) => Delay())
.Unwrap()
.ContinueWith((pre) => LongTimeMethod());
}
也就是说,当方法是async
时,整个事情要简单得多,而不是使用ContinueWith
:
private Task<string> BigMethod()
{
await Task.Run(() => LongTimeMethod1());
await Delay();
return await Task.Run(() => LongTimeMethod());
}
try this
private Task<string> BigMethod()
{
return Task.Factory.StartNew(() => LongTimeMethod1()).ContinueWith(async (pre) => await Delay()).ContinueWith((pre) => LongTimeMethod());
}