2017-06-07 30 views
1

我有有再次呼吁其他两个静态类方法如何创建静态类的简单的回调在C#

基本上在第一静态类,我想知道,一旦操作的方法的静态类在其他两个静态类

public static class FirstClass{ 

    public static async System.Threading.Tasks.Task FirstClassMethod() 
     { 
      SecondClass. SecondClassMethod(); 
      ThirdClass. ThirdClassMethod(); 
     } 
} 

public static class SecondClass{ 

    public static async System.Threading.Tasks.Task SecondClassMethod() 
     { 

     } 
} 

public static class ThirdClass{ 

    public static async System.Threading.Tasks.Task ThirdClassMethod() 
     { 

     } 
} 

解决我的问题的任何帮助下完成的,将不胜感激非常

+1

是否有一个特殊的原因,您为什么不等待这两种方法? –

回答

2

使用Task.WhenAll,您可以创建一个包装几个任务,当所有包裹任务完成完成单个任务。

public static class FirstClass{ 

    public static async System.Threading.Tasks.Task FirstClassMethod() 
     { 
      return await Task.WhenAll(
       SecondClass.SecondClassMethod(), 
       ThirdClass.ThirdClassMethod() 
      ); 
     } 
} 

public static class SecondClass{ 

    public static async System.Threading.Tasks.Task SecondClassMethod() 
     { 

     } 
} 

public static class ThirdClass{ 

    public static async System.Threading.Tasks.Task ThirdClassMethod() 
     { 

     } 
} 
1

随着await关键字的等待,直到Task完成。

using System.Threading.Tasks; 

public static async Task FirstClassMethod() 
{ 
    await SecondClass. SecondClassMethod(); 
    await ThirdClass. ThirdClassMethod(); 
    ... 
} 

BTW:

你应该考虑不使用等待只有当你确定你不想等待异步调用完成和被调用的方法不会提高任何例外。

+0

如果我不使用await来调用异步任务,它是否会抛出任何错误...纠正我如果我错了 –

+0

如果我不使用await,那么ThirdClassMethod可以在SecondClassMethod结束之前继续执行 –

+0

@RajanM Even如果你不使用await它可以抛出一个异常,但如果你想捕捉它,你需要做这样的事情'task.ContinueWith(t => HandleError(t.Exception), TaskContinuationOptions.OnlyOnFaulted);.'。如果你使用等待,你可以正常地捕捉它。 – NtFreX

相关问题