1

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());
}

1 Answer 1

1

Task.Factory.StartNew will by default use the current TaskScheduler.

The first time, you're not running inside a task, so the current TaskScheduler is the default TaskScheduler (which will run on the thread pool).

When you schedule handleResult back to the original context by using TaskScheduler.FromCurrentSynchronizationContext, that will run handleResult within a task on the main thread. So in that context, the current TaskScheduler is the UI TaskScheduler, not the default TaskScheduler.

To fix this, explicitly pass TaskScheduler.Default to any StartNew that you want to run on a thread pool thread (and remove LongRunning).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks its works, and thanks for the very clear explanation !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.