class Repository { public Task<entity> GetAllAsync(CancellationToken cancellationToken) { return Task.Run<entity>(() => { // тут что-то ресурсоёмкое вычисляем return entity; // возвращаем результат }); } }
The second example, the same with async await
class Repository { public async Task<entity> GetAllAsync(CancellationToken cancellationToken) { // вернёт управление в вызывающий код await Task.Yield(); // тут что-то ресурсоёмкое вычисляем return entity; // возвращаем результат } }
The third example, if you need to calculate something in parallel before returning the data
class Repository { public async Task<entity> GetAllAsync(CancellationToken cancellationToken) { var tasks = new List<Task>(); tasks.Add(Task.Run<entity>(() => { // тут что-то ресурсоёмкое вычисляем return entity; // возвращаем результат })); tasks.Add(Task.Run<entity>(() => { // тут что-то ресурсоёмкое вычисляем return entity; // возвращаем результат })); tasks.Add(Task.Run<entity>(() => { // тут что-то ресурсоёмкое вычисляем return entity; // возвращаем результат })); // дожидаемся окончания всех задач await Task.WhenAll(tasks); // дальше пробегаемся по списку задач, получаем результат работы каждой и что-то с ним делаем. И возвращаем уже вычисленный нами результат. } }
Of course, in a real combat application, the code will be slightly different and depend on a specific task, but the principle will be the same.
I note that async/await is a syntax wrapper over Task.Run with some differences. And the differences in exception handling in the process of performing the task.
But before writing an asynchronous code, be sure to read about async/await And the task otherwise there will be a lot of errors. Especially carefully you need to look at the exception handling.