开发者

Catching exceptions with BeginRead in C#

开发者 https://www.devze.com 2023-01-08 21:51 出处:网络
When using asynchronous code to read from streams etc using the BeginXXX / EndXXX pattern, I believe that any exceptions that occur during the process will be thrown when the call to EndXXX is made.

When using asynchronous code to read from streams etc using the BeginXXX / EndXXX pattern, I believe that any exceptions that occur during the process will be thrown when the call to EndXXX is made.

Does this mean that the initial call to BeginXXX will never throw an exception, it will always be thrown by EndXXX?

Or to put it another way, should I enclose BeginRead with try{}catch{} as well开发者_开发技巧?

public StartReading()
{
        // Should this be enclosed with try{}catch{} ?
        stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), stream);
}

private void readCallback(IAsyncResult result)
{
    Stream stream = (Stream)result.AsyncState;

    try
    {
        int len = stream.EndRead(result);

        // Do work...

    }
    catch(Exception ex)
    {
        // Error handling stuff.
    }
}


Well, any code can throw an exception, so "never" is strong... for example, OutOfMemoryException, ThreadAbortException, or some other exception that indicates resource saturation (for example, it somehow can't start the async operation).

It might (although I haven't tested) also throw immediately if that is a write-only stream. And it will certainly throw immediately if stream turns out to be null.

However! In all the cases I've mentioned, the correct behaviour is probably to let it bubble up; they all indicate pretty fundamental problems unrelated to the current logic. So no: I wouldn't try/catch here unless there was something specific I expected and wanted to handle somehow.


A simple proof:

public StartReading()
{      
    // Should this be enclosed with try{}catch{} ?
    buffer = null; // now it will throw
    stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), stream);
}

So Yes, you should anticipate on exceptions here.

0

精彩评论

暂无评论...
验证码 换一张
取 消