为什么base.method()不在C#中调用基类方法?

时间:2018-02-01 09:39:48

标签: c# stream networkstream

我有一个名为TCPStream的班级。它继承了NetworkStream类。 NetworkStream继承Stream Class,即

public class TCPStream : NetworkStream, IComparable<TCPStream>
{...}

public class NetworkStream : Stream
{...}

现在,Stream类有一个函数ReadAsync(,,,),此函数也覆盖了TCPStream类。

我的问题是:当我在base.ReadAsync(,,,)类中调用TCPStream时,它会再次执行自身......(不调用(父)Stream类方法。 ..)

因此,StackOverFlowException由于自我调用而发生..

我该怎么做才能完成这项任务? 代码段位于

之下
 public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
    {
        try
        {

            // int read_RetryCount = 0;
            // repeat till Complete Packet Received
            TimeSpan timeOutLimit = TimeSpan.MaxValue;
            if (CanTimeout)
                timeOutLimit = DateTime.Now.TimeOfDay + TimeSpan.FromMilliseconds(ReadTimeout);     // maxTimeOutLimit


                **// *** Here is Problem, base.ReadAsync(,,,) Not execute Parent's ReasAsync(,,,)***
                // *** After This Line, Function Execute itself Again..*****

                var length = base.ReadAsync(_localBuffer.Array, _localBuffer.Offset, _localBuffer.Count ).GetAwaiter().GetResult();

                Console.WriteLine("Total Bytes read = " + length);

        }
    }

1 个答案:

答案 0 :(得分:0)

现在你已经添加了代码,问题很明显:

你有:

public override Task<int> ReadAsync(byte[] buffer, int offset, int count,
    CancellationToken cancellationToken)
{
    ...
     var length = base.ReadAsync(_localBuffer.Array,
         _localBuffer.Offset, _localBuffer.Count ).GetAwaiter().GetResult(); 
}

现在看一下ReadAsync(byte[],int,int)的默认实现:

public Task<int> ReadAsync(byte[] buffer, int offset, int count) => 
    this.ReadAsync(buffer, offset, count, CancellationToken.None);

你没有调用你所覆盖的相同方法 - 你称之为一个非常微妙的不同方法。 问题是您没有传递取消令牌。如果你只是改为:

 var length = base.ReadAsync(_localBuffer.Array,
     _localBuffer.Offset, _localBuffer.Count, cancellationToken).GetAwaiter().GetResult();

它应该消失。

但请注意,您不应该像这样使用.GetAwaiter().GetResult()。更好的解决方案是将async修饰符添加到您的方法中,并使用:

 var length = await base.ReadAsync(_localBuffer.Array,
     _localBuffer.Offset, _localBuffer.Count, cancellationToken);

或者,丢失while(true)循环 - 它看起来非常错误 - 并且添加async修饰符,只是:

return base.ReadAsync(_localBuffer.Array,
     _localBuffer.Offset, _localBuffer.Count, cancellationToken);