Friday, May 27, 2011

Cool stuff in .NET 4.0: System.Threading.Tasks.TaskScheduler

private void Save()
{
    System.Threading.Tasks.TaskScheduler uiScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
    System.Threading.Tasks.Task<ErrorEnum>.Factory.StartNew(() =>
    {
        ErrorEnum callResult = ErrorEnum.OK;
        try
        {
            IsIdle = false;
            callResult = (ErrorEnum)DataContext.DomainRepository.SaveDomain(_domain);
            if (callResult != ErrorEnum.OK)
            {
                // If remote saving fails, rollback all the changes
                Rollback();
            }
            else
            {
                // If remote saving succeeds, save changes to local db
                SaveChangesToLocalDB();
            }
            return callResult;
        }
        catch (Exception ex)
        {
            LogManager.AddCMEventLog("DomainSettingsViewModel.Save", ex);
            // If anything goes wrong, rollback all the changes
            return ErrorEnum.LocalFatalAnonymousError;
        }
        finally
        {
            IsIdle = true;
        }
    }).ContinueWith(task => ShowResult(task.Result), uiScheduler);
}




This running tasks in background thread, then call UI thread to execute the ShowResult() function, Just like UIDispatcher

No comments:

Post a Comment