如何使用空方法体实现接口 returns IAsyncResult
How to implement an interface returns IAsyncResult with empty method body
如果我想继承ChannelBase
,WCF需要我实现像IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
这样的方法。因为当通道打开时我无事可做,所以我宁愿将该方法主体留空。在那些空方法中,我应该 return 和 IAsyncResult
什么?
根据经验,您根本不应该有空方法。如果 ChannelBase
有一个你不需要的抽象方法,你应该提供一个合理的覆盖,即使你现在不需要一个,或者从它抛出一个 NotSupportedException
,其中异常消息解释为什么不支持此方法:
public override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
throw new NotSupportedException("OnBeginOpen is not supported because...");
}
已通过将 IAsyncResult 实现添加为完整的异步结果来解决
internal class CompletedAsyncResult : IAsyncResult
{
public CompletedAsyncResult(object state)
{
this.AsyncState = state;
}
public object AsyncState { get; set; }
public WaitHandle AsyncWaitHandle => new ManualResetEvent(true);
public bool CompletedSynchronously => true;
public bool IsCompleted => true;
}
并像
一样使用
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
var result = new CompletedAsyncResult(state);
callback?.Invoke(result);
return result;
}
如果我想继承ChannelBase
,WCF需要我实现像IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
这样的方法。因为当通道打开时我无事可做,所以我宁愿将该方法主体留空。在那些空方法中,我应该 return 和 IAsyncResult
什么?
根据经验,您根本不应该有空方法。如果 ChannelBase
有一个你不需要的抽象方法,你应该提供一个合理的覆盖,即使你现在不需要一个,或者从它抛出一个 NotSupportedException
,其中异常消息解释为什么不支持此方法:
public override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
throw new NotSupportedException("OnBeginOpen is not supported because...");
}
已通过将 IAsyncResult 实现添加为完整的异步结果来解决
internal class CompletedAsyncResult : IAsyncResult
{
public CompletedAsyncResult(object state)
{
this.AsyncState = state;
}
public object AsyncState { get; set; }
public WaitHandle AsyncWaitHandle => new ManualResetEvent(true);
public bool CompletedSynchronously => true;
public bool IsCompleted => true;
}
并像
一样使用protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
var result = new CompletedAsyncResult(state);
callback?.Invoke(result);
return result;
}