You can use the resources of TPL, with it you can run any synchronous condigo asynchronously, Follow 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 Go method, before it I called a Writeline, and after it called another Writeline.
If the execution of the go was synchronous, the Writeline after the go call would only be executed after the code "printd" all generated entities.
Output of the method:
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 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 just replace the Vai method with 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);
}
}
Please specify which framework/technologies you are using, and add the corresponding tags.
– dcastro
I’m using Azure Tables but I’m not allowed to create a new tag.
– douglaslps
Qando so, write in the body of the question the technology. Need another tag? Or that I change this?
– Maniero
I am not familiar with Azure Tables, but in other technologies there is
BeginExecuteQuery
. This would not be the case?– Wagner DosAnjos
Have you tried a separate thread using a thread pool?
– renanleandrof
@Renanlf from what I understood this would be properly async, it would be something like asynchronous about synchronous. I was thinking about using Executesegmentedasync or something like that. Ideas?
– douglaslps
Ué, vc will have control of your thread execution, then you just need to define the behavior of the main while the other thread is running ;)
– renanleandrof