C # - convert an async task from one type to another

I'm used to working with the Scala programming language - using Scala, I could map futures, for example:

val response: Future[HttpResponse] = asyncHttpClient.GetRequest("www.google.com")

val statusCode: Future[Int] = response.map(r => r.statusCode)

Recently, I picked up work with C #, and I saw myself in the same situation as in the example above, however, I could not understand how to "map" the task.

Here is an example of what I want to achieve:

Task<HttpResponseMessage> response = httpClient.GetAsync("www.google.com")

Task<int> statusCode = response.Map(response => response.StatusCode)

thank

+4
source share
2 answers

The most direct translation with existing methods:

Task<int> statusCode = response.ContinueWith(t => t.Result.StatusCode)

However, in practice, you almost always wait for a task to get a result. Perhaps you should take a peek at async / wait.

+5
source

, , . ( , ). , :

public static async Task<TResult> Map<TSource, TResult>
    (Task<TSource> task, Func<TSource, TResult> selector)
    => selector(await task);
+4

Source: https://habr.com/ru/post/1649542/


All Articles