How can I use the signature of the Task.Run (Func <Task> f) method?
To use this method:
public static Task Run(Action action)
I just write:
void MyMethod(){ //do something }
Task t = Task.Run(new Action(MyMethod));
However, I do not understand how to use the following overload
public static Task Run(Func<Task> f)
Msdn mentions that the returned task is a "proxy for the task returned by f", which further confuses me. What is meant by a proxy server and what can I call this method?
Func<Task>is just a function that returns a task. Then this task is performed.
So, Task Run( Func<Task> f )returns a Task, whose task is to start another Task(created f). This is what is meant by proxies.
However, read the MSDN note (highlighted by me):
Run<TResult>(Func<Task<TResult>>)asyncawait. .
, , Task.Run. , a Func<T> - , . :
public Func<bool> IsValid = this.ValidateUser;
public bool ValidateUser() { return someUser.IsAuthenticated; }
public Func<bool> IsValidUser = this.User.IsAuthenticated;
, , bool.
public void Foo()
{
if (!IsValidUser()) throw new InvalidOperationException("Invalid user");
}
, , , .
Func<int, bool> IsUserAgeValid = (age) => return age > 18;
// Invoke the age check
bool result = this.IsUserAgeValid(17);
, Func. , , .
A Func<Task> awaitable Task.Run.
, await , .
public Task Foo()
{
/* .. do stuff */
}
public void Bar()
{
Task.Run(async () =>
{
await Foo();
/* do additional work */
});
}
Foo(), Task.Run Foo.
Task.Run(Foo);
, , Task.Run, , , ContinueWith.
public void Bar()
{
Task.Run(Foo).ContinueWith(foosTaskResult =>
{
/* Do stuff */
});
}
MSDN, , f, ,
Task returnedTask = Task.Run(Foo);
returnedTask , Foo().
a Func<T>refers to a method that returns Twhat is in this case Task. Thus, to make it MyMethodcompatible with this particular overload, you must write
Task MyMethod() {...}
It also means that you can make a method MyMethodand asyncthus
async Task MyMethod() {...}
When referring to the "proxy", this means that the Taskreturned Task.Runone is not really the task returned MyMethod, but instead completes it.