I have Client
and Server
classes.
The Server
return a ResultWithNestedTask
instance.
public class ResultWithNestedTask
{
public Task<String> NestedTask;
public string Result;
}
The Client
displays the data from Result
, then waits for the completion of NestedTask
and displays the result from NestedTask
.
The Server
:
- Starts a new
Task
and waits for the result - Starts a nested task and returns the task to the client
- Waits for the nested task to complete before doing some work with result.
Server's method DoWorkAsync
:
static async Task<ResultWithNestedTask> DoWorkAsync()
{
// start new Task and wait result
var resultTask = await Task<String>.Factory.StartNew(() =>
{
return "Result task.";
});
//start neasted task
var resultNestedTask = Task<String>.Factory.StartNew(() =>
{
Task.Delay(TimeSpan.FromSeconds(5)).Wait(); //wait while return data
return "Result neasted task.";
});
//do some work whith nested task
Task.Factory.StartNew(() =>
{
resultNestedTask.Wait();
var resultFromNestedTask = resultNestedTask.Result;
resultFromNestedTask = "Updated string";
Console.WriteLine(resultFromNestedTask);
});
//return result string and neasted task to the client
return new ResultWithNestedTask()
{
NestedTask = resultNestedTask,
Result = resultTask,
};
}
Client:
var taskResult = await DoWorkAsync();
// writeline result string
Console.WriteLine(taskResult.Result);
// client wait NestedTask
var nestedTask = await taskResult.NestedTask;
// writeline result string from nested task
Console.WriteLine(nestedTask);
This code should not block the UI.
The server returns the nested task and doesn't wait for the nested task to finish.
//do some work with the nested task
Task.Factory.StartNew(() =>
{
resultNestedTask.Wait();
var resultFromNestedTask = resultNestedTask.Result;
resultFromNestedTask = "Updated string";
Console.WriteLine(resultFromNestedTask);
});
I want to return the result before the task completes.
Client and Server are abstractions, and just one class takes data from another class.
Is this normal code? Do you see any problems?