Why are async callback socket methods usually static? (assume I understand static class, method and data objects). Would there be a fundamental design/logic error if one were to write a class using these as instance methods? Is there anything special that one should be careful to avoid?
Why are async callback socket methods usually static? (assume I understand static class, method
Share
There is no specific reason that they should be static. It all depends on your design.
If the callback needs to access members in the class then it can be declared as a instance member. However, you will need to make sure that you correctly syncronize the access to the instance members because the callback can be invoked concurrently from different threads.
I guess the examples you looked at all passed the required data through to the callback through the
IAsyncResult.AsyncStateso did not require additional information from the class. If you can do this it can simplify your code, since you no longer need to worry about thread syncronization etc..Update
Just to clarify, based on the comments it seems I should have beed more explicit. It is not that the static callback would be thread safe, but rather that in a design where the data required is passed to the callback and of course this data is not shared by other threads then locking is not required. And since the callback is passed all the data it requires, it does not need access to the class instance and can therefore be made static.