استفاده از Async&Await برای پیاده سازی متد های Async
نویسنده: مسعود پاکدل
تاریخ: ۱۳۹۱/۱۱/۲۳ ۱۴:۲۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}public class ProductService
{
public ProductService()
{
ListOfProducts = new List<Product>();
}
public List<Product> ListOfProducts
{
get;
private set;
}
private void InitializeList( int toExclusive )
{
Parallel.For( 0 , toExclusive , ( int counter ) =>
{
ListOfProducts.Add( new Product()
{
Id = counter ,
Name = "DefaultName" + counter.ToString()
} );
} );
}
public IAsyncResult BeginGetAll( AsyncCallback callback , object state )
{
var myTask = Task.Run<IEnumerable<Product>>( () =>
{
InitializeList( 100 );
return ListOfProducts;
} );
return myTask.ContinueWith( x => callback( x ) );
}
public IEnumerable<Product> EndGetAll( IAsyncResult result )
{
return ( ( Task<IEnumerable<Product>> )result ).Result;
}
}class Program
{
static void Main( string[] args )
{
GetAllProducts().ToList().ForEach( ( Product item ) =>
{
Console.WriteLine( item.Name );
} );
Console.ReadLine();
}
public static IEnumerable<Product> GetAllProducts()
{
ProductService service = new ProductService();
var output = Task.Factory.FromAsync<IEnumerable<Product>>( service.BeginGetAll , service.EndGetAll , TaskCreationOptions.None );
return output.Result;
}
} public async Task<IEnumerable<Product>> GetAllAsync()
{
var result = Task.Run( () =>
{
InitializeList( 100 );
return ListOfProducts;
} );
return await result;
}class Program
{
static void Main( string[] args )
{
GetAllProducts().Result.ToList().ForEach( ( Product item ) =>
{
Console.WriteLine( item.Name );
} );
Console.ReadLine();
}
public static async Task<IEnumerable<Product>> GetAllProducts()
{
ProductService service = new ProductService();
return await service.GetAllAsync();
}
}