I'm used to working with the Scala programming language - using Scala I could map over futures, such as:
val response: Future[HttpResponse] = asyncHttpClient.GetRequest("www.google.com")
val statusCode: Future[Int] = response.map(r => r.statusCode)
Recently I've picked up working with C#, and I saw myself being in the same situation as the example above, however I couldn't figure out how "map" a 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)
Thanks
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
C is a procedural language that provides no support for objects and classes. C++ is a combination of OOP and procedural programming languages. C has 32 keywords and C++ has 63 keywords. C supports built-in data types, while C++ supports both built-in and user-defined data types.
The most direct translation with existing methods would be:
Task<int> statusCode = response.ContinueWith(t => t.Result.StatusCode)
However in practice you almost always await the task to get the result. Maybe you should look into async/await.
I'm slightly surprised there isn't anything in the framework for this, to be honest. (More likely, there is an I haven't seen it.) You can build it fairly easily though:
public static async Task<TResult> Map<TSource, TResult>
(Task<TSource> task, Func<TSource, TResult> selector)
=> selector(await task.ConfigureAwait(false));
Note: using ConfigureAwait
here isn't always clear-cut. You may want to include a continueOnCapturedContext
parameter:
public static async Task<TResult> Map<TSource, TResult>(
Task<TSource> task,
Func<TSource, TResult> selector,
bool continueOnCapturedContext = false) =>
selector(await task.ConfigureAwait(continueOnCapturedContext));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With