如何从另一个方法调用异步方法

时间:2016-12-12 16:47:05

标签: c# async-await

我很难从当前的方法调用异步方法。 试着做这样的事情:

int i;
public void Method1() {
    while (statement1) {
        ~code~
        Method2(i);
    }
    while (statement2) {
        ~code~
        Method2(i);
    }
}

public async void Method2(int i) {
    if(statement){
        ~code~
        await Task.Delay(2000);
    }
    else
    {
        ~code~
        await Task.Delay(2000);
    }
}

所以我希望基本上Method2是一个控制流的方法(使用另一种方法来改变图片框中的图片),但是我无法让它工作,当它工作时它永远不会延迟任何事情。有谁知道我做错了什么? Method2最终会更改Method1的语句。

3 个答案:

答案 0 :(得分:0)

您应该使Method1同步,并为Method2调用添加await运算符:

public async Task Method1() {
    while (statement1) {
        ~code~
        await Method2(i);
    }
    while (statement2) {
        ~code~
        await Method2(i);
    }
}

public async Task Method2(int i) {
    if(statement){
        ~code~
        await Task.Delay(2000);
    }
    else
    {
        ~code~
        await Task.Delay(2000);
    }
}

如果由于某种原因需要Method1同步,则应该从Method2返回的任务上调用Wait()。然而,它被认为是不好的做法,因为你失去了.NET线程池的优势。

答案 1 :(得分:0)

对于另一种能够等待Method2的方法,后者必须返回一个返回类型为Task或Task(而不是void):

public async Task Method2(int i) {
if(statement){
    ~code~
    await Task.Delay(2000);
}
else
{
    ~code~
    await Task.Delay(2000);
}

然后应将Method1标记为async并等待Method2:

public async void Method1() {
while (statement1) {
    ~code~
    await Method2(i);
}
while (statement2) {
    ~code~
    await Method2(i);
}
}

答案 2 :(得分:0)

async / await的best practice是使用async"一直向下" (除非你真的并且真的不关心Method1等待Method2完成)。

可以将Task.Wait(或类似结构)与异步代码混合使用,但它只是bad idea,因为它可能会导致死锁。

正如其他人所指出的那样,最好的事情就是让Method1同步:

public async Task Method1() {
while (statement1) {
    await Method2(i);
    // ...
}

请注意,您必须让Method1也返回一个任务,否则您无法等待它:

public async Task Method2

这可能是XY Problem的情况,因为您提供的代码示例没有理由首先是异步(或者甚至是单独的方法) - 你可以只做Thread.Sleep。此外," if"声明毫无意义,因为根据你向我们展示的内容,你无论如何都会延迟2秒。如果你能展示一个更实质的代码示例,这将有所帮助,这样我们就可以更好地了解你正在尝试做什么,这样我们就可以推荐async在这里是否是一个合适的解决方案。

最后一点:async / await的目的之一是允许调用线程在等待结果时执行其他工作 - 例如,如果要在不使用&#34的情况下下载文件;悬挂"用户界面。我已经看到很多人使用异步/等待的方式,基本上可以避免这个目的。例如:

static void Main(string[] args) {
     // This is a terrible thing to do but it's for illustration purposes
     Task task = Method1();
     task.Wait();

     // Some other work
 }

 private static async Task Method1() {
     await Method2();
     // Some other work
 }

 private static async Task Method2() {
     await Method3();
     // Some other work
 }

 private static async Task Method3() {
    await Task.Delay(1000);
 }

这是一个非常愚蠢的例子,被授予,但在这种情况下,async / await完全没有意义,因为它无论如何只是按顺序执行每个动作。

相关问题