Hi, I just cannot figure out what why IAsyncResult is an interface instead of simple object. As I remember correctly, interface contains only method names without implementation so I canot see how it is used here as I do not derive any class of it nor override its methods? I am just confused..Thanks
Like this, the result can be any type of object, which implements the IAsyncResult interface.
You're right that an interface only contains methods/properties without implementation. In this case, it is garanteed that the AsyncResult object contains the methods which are needed by the 'Async-framework'.
The IAsyncResult contains four properties:
- AsyncState (Object)
- AsyncWaitHandle (WaitHandle)
- CompletedSynchronously (Boolean)
- IsCompleted (Boolean)
Those properties are simply required when working with Async methods. If it would be an object, you would be less flexible I think.
If it were just an object, it could be anything - and you could not rely on certain properties and/or methods being present, like you can when you know you'll get an object that implements the interface IAsyncResult
.
Since the object you're getting back must be implementing the interface in question, you can rely on the fact that the properties AsyncState
, AsyncWaitHandle
, CompletedSynchronously
and IsCompleted
will be present.
If you had just an object and you got back an int
- how would you get those properties you need??
Because an "ASyncResult" in itself is nothing concrete.
Because C# only allows single inheretance, by making it an interface you can implement it on any object type you choose.
For example, if I my method returns type Foo, I can create an async return type for my app simply by creating a subclass saying
FooAsync : Foo, IAsyncResult
And simply cast it as opposed writing code to extract values.