A
A
Andrew10000002013-10-26 00:18:02
C++ / C#
Andrew1000000, 2013-10-26 00:18:02

Asynchronous Operations in C#: Handling Exceptions

Interested in how to properly handle exceptions when performing asynchronous operations in C#.
For example, an asynchronous method is called from the code
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
. Let's say we wrapped it in a try ... catch.
Further, Callback is triggered
public static void ListenerCallback(IAsyncResult result) { }
Inside this method, it is also necessary to write try ... catch?
In which case will the exception occur in the first block (execution context) and in which case in the second?

But most of all, a specific question is of interest: if, for example, the connection breaks, where in the code will the exception occur, and is the ListenerCallback guaranteed to be called? It's just that in this method, the first operator must be a command that must be executed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shai_hulud, 2013-11-05
@shai_hulud

BeginGetContext should also be wrapped (unless MSDN says it doesn't throw exceptions)
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
and inside the listener.EndGetContext(result) callback, which will throw an exception that could happen inside the asynchronous operation.

B
Barsik107, 2013-11-13
@Barsik107

You can also use something like Task for asynchronous operations: http://msdn.microsoft.com/ru-ru/library/system.threading.tasks.task (v=vs.110).aspx

It has an Exception field that can be used for this purpose.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question