S
S
sudo rm -rf /2021-10-06 12:19:40
C++ / C#
sudo rm -rf /, 2021-10-06 12:19:40

How to cast a Task set with different returned results to a Task set with results as a common interface?

Good afternoon.

I am writing an asynchronous network library that has several options for returning packets: BasicStatisticResponse , FullStatisticResponse . All packages implement the common IResponse interface .

Response class diagram

615d657700f70688520771.png


Accordingly, each type of response has its own request method.
public async Task<ServerBasicStateResponse> GetBasicStatus(Server server);
public async Task<ServerFullStateResponse> GetFullStatus(Server server);


The problem arises when we want to store working tasks in one list List<Task<IResponse>> requestsfor later use in Task.WaitAll(requests).

List<Task<IResponse>> serversStatisticRequests = new();
foreach(Server server in servers)
{
  serversStatisticRequests.Add(service.GetBasicStatus(server));
  serversStatisticRequests.Add(service.GetFullStatus(server));
}


Swears at something that Task<ServerBasicStateResponse>is Task<FullStatisticResponse>impossible to lead to Task<IResponse>.

What can be done about it?
It would not be desirable to allocate a base class in the presence of an interface.
Returning a value from both methods in the form of an IResponse is the same: we will not necessarily always shove everything into a heap. When using it, we may only need queries of a particular type, and we would not want to cast their results to the desired type each time: we expect the library to know what type of response comes to which type of request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-10-06
@vabka

You can wrap it up like this:

serversStatisticRequests.Add(service.GetBasicStatus(server).ContinueWith(x => (IResponse) x.Result));
serversStatisticRequests.Add(service.GetFullStatus(server).ContinueWith(x => (IResponse) x.Result));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question