C# TaskStatus.RanToCompletion: Understanding Task Completion in C#
In C#, 'TaskStatus.RanToCompletion' is an enum value that represents the status of a task when it has completed successfully without any exceptions.
When a task is created, it is assigned a status based on its progress. If the task has completed successfully, its status will be 'TaskStatus.RanToCompletion'. This means that the task has finished executing all of its code without any errors or exceptions.
Here's an example of how to check if a task has completed successfully using the 'TaskStatus' enum:
Task<int> task = Task.Run(() =>
{
// Some code here
return 42;
});
// Wait for the task to complete
task.Wait();
if (task.Status == TaskStatus.RanToCompletion)
{
int result = task.Result;
Console.WriteLine('Task completed successfully with result: ' + result);
}
In the above example, the 'Task
It's important to note that accessing the 'Result' property of a task that has not completed will block the current thread until the task is finished. To avoid this, you can use 'await' instead of 'Wait()' to asynchronously wait for the task to complete.
原文地址: https://www.cveoy.top/t/topic/l8ZJ 著作权归作者所有。请勿转载和采集!