I have to load some object from Azure. I planned to load them five by five in order to take less time (kind of lazy loading) :
ProductManager.LoadProduct call my ProductAccess.LoadProduct This last method load product from azure, and then raise an event in order that the manager can get the product. Then if it receive product, it call again ProductAccess.LoadProduct. etc ....
Can't use await/async because it's cross platform code (monodroid/monotouch stable version still don't have await/async).
The first load is correct, then the second call works, but seems my task is not executed (the start do not execute my second task...). I check the thread number and the second time, the Task.Factory.StartNew(() => is executed on the main thread. I try to fix it by specify a long running but still doesn't work.
Here is my code :
Manager side :
public void LoadProduct()
{
ProductAccess.LoadProductsAsync()
}
public void receiveProductsAsync(Object pa, EventArgs e)
{
if (((ProductEventArgs)e).GetAttribute.Equals("LoadProductsAsync"))
{
IoC.Resolve<IProductAccess>().RequestEnded -= receiveProductsAsync;
if ( ((ProductEventArgs)e).LP).Count() != 0)
LoadProductsAsync();
Products = Products.Concat(((ProductEventArgs)e).LP).ToList();
if (((ProductEventArgs)e).E != null)
{
if (RequestEnded != null)
RequestEnded(this, new OperationEventArgs() { Result = false, E = ((ProductEventArgs)e).E, GetAttribute = "LoadProductsAsync" });
}
else
{
if (RequestEnded != null)
{
RequestEnded(this, new OperationEventArgs() { Result = true, GetAttribute = "LoadProductsAsync" });
}
}
}
}
Access side :
public void LoadProductsAsync()
{
Task<ProductEventArgs>.Factory.StartNew(() =>
{
var longRunningTask = new Task<ProductEventArgs>(() =>
{
try
{
var _items = this.table.Select(x => new Product(.....)).Skip(nbrProductLoaded).Take(nbrProductToLoadAtEachTime).ToListAsync().Result;
this.nbrProductLoaded += _items.Count();
Task.Factory.StartNew(() => synchronizeFavorite(_items));
return new ProductEventArgs() { LP = _items, GetAttribute = "LoadProductsAsync" };
}
catch (Exception e)
{
return new ProductEventArgs() { E = e, GetAttribute = "LoadProductsAsync" };
}
}, TaskCreationOptions.LongRunning);
longRunningTask.Start();
if (longRunningTask.Wait(timeout))
return longRunningTask.Result;
return new ProductEventArgs() { E = new Exception("timed out"), GetAttribute = "LoadProductsAsync" };
}, TaskCreationOptions.LongRunning).ContinueWith((x) => {
handleResult(x.Result);
}, TaskScheduler.FromCurrentSynchronizationContext());
}