Secretary Of Education
Secretary Of Education

Reputation: 109

Predefined task return async many times

I have a task defined at the top of my class like this:

Task<string> MainTask {get;set;}

And then inside of application I build this task.

MainTask = new Task<string>( () => 
{
    return Task.Run<string>( async () => 
    {
        await GetResult();

    }).Result;
});

I want to make a loop until the task returns data but once the task finishes first time I cannot start it again.

bool gotResult = false;
While(gotResult == false)
{
  MainTask.Start();
  MainTask.Wait();
  if(MainTask.Result)
  {
    gotResult = true;
  }
}

Upvotes: 0

Views: 64

Answers (1)

Servy
Servy

Reputation: 203822

MainTask shouldn't be a Task, it should be a Func<Task> (or, in this case, since the asynchronous operation appears to provide a boolean, a Func<Task<bool>>, allowing you to start the asynchronous operation any time you want by simply invoking the method.

So define it as:

Func<Task<bool>> AsyncOperation {get;set;}

Use it as:

while(!await AsyncOperation())
{
    //do nothing
}

As for assigning it, you simply need to assign the asynchronous method you have:

AsyncOperation = GetResult;

Note that you really shouldn't use the Task constructor every really. Don't deal with unstarted tasks, it only causes confusion. There's also no need to use Task.Run to call an asynchronous method. It's already asynchronous. There's also no need to use an async lambda to call an asynchronous method, both of those things are just adding overhead and adding no value.

Upvotes: 2

Related Questions