Donate

Return Multiple Values From C# Asynchronous Function

Good evening fellow developers!

I have a simple application that queries the database and returns list of employees and list of their dependents. Since I've just started learning async programming, I wonder if I could return multiple values for an asynchronous function or method. The initial solution that I have is to create a view model class that has two properties specifically list of employees and list of dependents. And this view model class will be the return type of the function. After reading through the docs, it's possible to return multiple values using System.ValueTuple namespace. If the target framework of the project is 4.6.2 and below, you need to add the System.ValueTuple NuGet package using NuGet Console Manager or add the package using Manage NuGet Package tool. For now, lets install the package using console manager.
Install-Package "System.ValueTuple"
Next is to modify the existing method to return multiple values using System.ValueTuple.
private static async Task<(List<clsEmployees>, List<clsEmployeeDependents>)> GetEmployeeDependents()
{
 Task task;
 CancellationTokenSource tokenSource;
 CancellationToken token;
 UnitOfWork unitOfWork;

 errMessage = string.Empty;
 token = new CancellationToken();
 tokenSource = new CancellationTokenSource();
 unitOfWork = new UnitOfWork(new clsEmployeeQuery());

 try
 {
  token = tokenSource.Token;
  task = new Task(() =>
  {
   //DB method to return employees and their dependents
   if (!unitOfWork.EmployeeRepository.GetUsers(ref lstEmployees, ref lstEmployeeDependents, ref errMessage))
    tokenSource.Cancel();
  }, token);

  task.Start();
  await task;
 }
 catch (Exception ex)
 {
  Log("clsProcessor.cs", "GetEmployeeDependents()", ex, errMessage);
  return (null, null);
 }

 if (!string.IsNullOrEmpty(errMessage))
  return (null, null);

 return (lstEmployees, lstEmployeeDependents);
To call the method in main function and retrieve the values, simply access them using Item1...N properties.
var employeeResult = GetEmployeeDependents().Result;
List<clsEmployees> lstEmp = employeeResult.Item1;
List<clsEmployeeDependents> lstEmpDep = employeeResult.Item2;

Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input