开发者

Questions about IAsyncResult implementation

My instant messaging library takes advantage of the Begin/End asynchronous pattern for most (if not all) communications sent across a socket which wait for an acknowledgement.

As such, I find myself implementing IAsyncResult for quite a large number of operations. (ChangeNicknameOperation, SendMessageOperation, AddUserOperation etc..)

I decided to create a base class for my async operations called AsyncOperationBase, which contains the standard implementation of IAsyncResu开发者_开发百科lt, including methods to set the operation as complete.

Is this a common practice? I feel like it's a little unnecessary given that the code being repeated is rather minimal.

Also, when calling the AsyncResult's callback, is it recommended to call it on another thread, or is it perfectly legitimate to call on the thread which completes the operation?

Thanks


For your problem the new async/await kewords in C# 5 would be the best solution. But until it is released it is fine to go with a base class. To back up my claim I have looked with Reflector at the classes that do implement IAsyncResult in the BCL and there is one big base clas called System.Net.LazyAsyncResult from which 20 other classes derive from. So yes it is a good practice and it will only get easier until we have C# 5.

Here is the list of classes that derive from LazyAsyncResult:

internal class System.Net.ContextAwareResult
internal class System.Net.ListenerClientCertAsyncResult
internal class System.Net.ListenerAsyncResult
internal class System.Net.HttpRequestStream/HttpRequestStreamAsyncResult
internal class System.Net.HttpResponseStreamAsyncResult
internal class System.Net.NestedMultipleAsyncResult
internal class System.Net.NestedSingleAsyncResult
internal class System.Net.WorkerAsyncResult
internal class System.Net.Cache.CombinedReadStream/InnerAsyncResult
internal class System.Net.Cache.ForwardingReadStream/InnerAsyncResult
internal class System.Net.BufferAsyncResult
internal class System.Net.Base64Stream/ReadAsyncResult
internal class System.Net.Base64Stream/WriteAsyncResult
internal class System.Net.BufferedReadStream/ReadAsyncResult
internal class System.Net.Mime.MimeBasePart/MimePartAsyncResult
internal class System.Net.Mime.MultiAsyncResult
internal class System.Net.Mime.QuotedPrintableStream/WriteAsyncResult
internal class System.Net.Mail.SmtpConnection/ConnectAndHandshakeAsyncResult
internal class System.Net.Mail.SmtpReplyReaderFactory/ReadLinesAsyncResult
internal class System.Net.Mail.SendMailAsyncResult

Yours, Alois Kraus

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜