You can use the features of TPL , with it can rotate any synchronous status asynchronously, Here is an example.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Vai iniciar a criação de entities");
Vai();
Console.WriteLine("Criação iniciada de entities");
Console.ReadLine();
}
private static async void Vai()
{
var myEntities = await RunWriteLineAsync(10);
Console.WriteLine("Criação finalizada");
foreach (var myEntity in myEntities)
{
Console.WriteLine("myEntity: {0}", myEntity.Nome);
}
}
private static Task<IEnumerable<MyEntity>> RunWriteLineAsync(int total)
{
var tcs1 = new TaskCompletionSource<IEnumerable<MyEntity>>();
Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
var entities = new List<MyEntity>();
for (int i = 0; i < total; i++)
entities.Add(new MyEntity { Nome = i.ToString() });
tcs1.SetResult(entities);
});
return tcs1.Task;
}
}
public class MyEntity
{
public string Nome { get; set; }
}
}
As you can see, I called the method Go, before it I called a WriteLine, and after it I called another WriteLine.
If the execution of the goes was synchronous, the WriteLine after the call of the goes, would only be executed after the code "printar" all the entities generated.
Method Output:
Vai iniciar a criação de entities
Criação iniciada de entities
Criação finalizada
myEntity: 0
myEntity: 1
myEntity: 2
myEntity: 3
myEntity: 4
myEntity: 5
myEntity: 6
myEntity: 7
myEntity: 8
myEntity: 9
Output of the method if it was executed synchronously:
Vai iniciar a criação de entities
Criação finalizada
myEntity: 0
myEntity: 1
myEntity: 2
myEntity: 3
myEntity: 4
myEntity: 5
myEntity: 6
myEntity: 7
myEntity: 8
myEntity: 9
Criação iniciada de entities
To check the second output is just to replace the method Go, by this:
private static void Vai()
{
var myEntities = RunWriteLineAsync(10);
myEntities.Wait();
Console.WriteLine("Criação finalizada");
foreach (var myEntity in myEntities.Result)
{
Console.WriteLine("myEntity: {0}", myEntity.Nome);
}
}