2015-04-01 204 views
0

好吧!这已经在几个小时里给我强调了。c#接口实现异步等待

我使用所提供的组件有一个接口,我需要实现

public interface ICustomInterface 
{ 
     CustomType DoSomething(string name); 
} 

在我的代码我这样做:

public class MyClass: ICustomInterface 
{ 
    public MyClass() 
    { 
    } 

    // now I should implement the interface like this 

    public CustomType DoSomething(string name) 
    { 
      CustomType nType = new CustomType(); 

      // do some work 

      return nType; 
    } 
} 

到目前为止好,但在我执行MyClass I中的接口需要使用async await因此实现应该是这样的:

public class MyClass: ICustomInterface 
{ 
    public MyClass() 
    { 
    } 

    // now I should implement the interface like this 

    public async Task<CustomType> DoSomething(string name) 
    { 
      CustomType nType = new CustomType(); 

      await CallSomeMethodAsync(); 

      // do some extra work 

      return nType; 
    } 
} 

当然,这不起作用,因为它抱怨接口​​没有实现。

是否有一种方法来覆盖接受异步等待的接口实现?我不能修改提供的组件。

+2

你不能那样做。 – SLaks 2015-04-01 19:44:59

+0

寻找答案:http://stackoverflow.com/questions/13573516/interfaces-and-async-methods – maximdumont 2015-04-01 19:45:10

回答

4

这是不可能的。如果接口要求同步计算操作,则需要同步执行操作。

+0

然后我将如何使用我的异步操作呢? – 2015-04-01 19:48:18

+1

@DavidDury既可以同步执行操作,也可以不是异步执行操作,也可以不实现接口(可能使用不同的接口)。这当然是因为你无法修改有问题的界面。 – Servy 2015-04-01 19:48:47

+0

我期待着这个答案,在过去的3个小时里尝试了一切......但谢谢澄清! – 2015-04-01 19:51:06