2015-09-25 39 views
3

我的问题是为什么延迟方法不起作用(整个操作不等待4秒),60%没有显示在lable1内部。延迟继续现在正在工作

为了更精确的操作顺序应该是这样和整个操作应采取8 seconds.but它需要4秒,刚内LongTimeMethod1()Thread.Sleep(4000)工作

LongTimeMethod1()//delay for 4 sec,show 60% 
delay()//delay for 4 sec 
LongTimeMethod()//40% imidiatly 

我知道我可以写代码只是等待和异步,但我想知道我在这段代码中做错了什么。

private void button1_Click(object sender, EventArgs e) 
    { 
     CallBigMethod(); 
     label1.Text [email protected]"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%..."; 
    } 
+0

@PetSerAl它只是解决了时间问题,但它不能解决显示60%的问题 –

回答

0

试试这个

private Task<string> BigMethod() 
    { 

     return Task.Factory.StartNew(() => LongTimeMethod1()).ContinueWith(async (pre) => await Delay()).ContinueWith((pre) => LongTimeMethod()); 
    } 
+0

什么也没有改变 –

+0

没有任何理由在'ContinueWith'中使用'async' lambda。它什么都不做。这与OP的代码相同。 – Servy

5

Task通过.ContinueWith((pre) => Delay())返回实际上是一个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()); 
} 
+0

感谢代码,它解决了时间问题,它需要8秒,但仍然没有在标签中显示60% –

+0

@E_N_Y这是因为'LongTimeMethod'返回40%,而不是60%。如果你切换'LongTimeMethod'和'LongTimeMethod1'的位置,那么结果会改变。如果您对这些方法使用了更有意义的(或至少可区分的)名称,那么这可能会更少混淆。 – Servy

+0

所以你的意思是我没有办法显示60%,然后4秒延迟,然后用这个代码打印40%?!我知道如果我改变我可以导致的方法会不同:) –