Ejemplo n.º 1
0
        /// <summary>
        /// Ui主线程调用
        /// </summary>
        /// <param name="action">执行方法</param>
        public static void Invoke(Action action)
        {
            if (action == null)
            {
                return;
            }
            if (_mainThreadAsyncDispatcher == null)
            {
                Task.Run(async() =>
                {
                    await SemaphoreSlim.WaitAsync();

                    try
                    {
                        if (_mainThreadAsyncDispatcher == null)
                        {
                            if (MvvmCross.Mvx.IoCProvider != null &&
                                MvvmCross.Mvx.IoCProvider.CanResolve(typeof(IMvxMainThreadAsyncDispatcher)))
                            {
                                _mainThreadAsyncDispatcher =
                                    MvvmCross.Mvx.IoCProvider.Resolve <IMvxMainThreadAsyncDispatcher>();
                            }
                            else
                            {
                                do
                                {
                                    await Task.Delay(5);

                                    if (MvvmCross.Mvx.IoCProvider != null &&
                                        MvvmCross.Mvx.IoCProvider.CanResolve(typeof(IMvxMainThreadAsyncDispatcher)))
                                    {
                                        _mainThreadAsyncDispatcher = MvvmCross.Mvx.IoCProvider
                                                                     .Resolve <IMvxMainThreadAsyncDispatcher>();
                                        break;
                                    }
                                } while (_mainThreadAsyncDispatcher == null);
                            }
                        }
                    }
                    finally
                    {
                        SemaphoreSlim.Release();
#pragma warning disable 4014
                        _mainThreadAsyncDispatcher?.ExecuteOnMainThreadAsync(action);
#pragma warning restore 4014
                    }
                });
            }
            else
            {
                _mainThreadAsyncDispatcher.ExecuteOnMainThreadAsync(action);
            }
        }
Ejemplo n.º 2
0
        public async Task <IDisposable> Connect(InternalObservableCollection <T> collection)
        {
            MvxNotifyCollectionChangedEventSubscription subscription = null;
            await _dispatcher.ExecuteOnMainThreadAsync(() =>
            {
                lock (_lock)
                {
                    collection.LockedAction(content =>
                    {
                        _items.ReplaceWith(content);
                        subscription = content.WeakSubscribe(UiCollectionChanged);
                    });
                }
            }).ConfigureAwait(false);

            return(subscription);
        }
Ejemplo n.º 3
0
        public override void ViewAppeared()
        {
            base.ViewAppeared();

            _ = _dispatcher.ExecuteOnMainThreadAsync(() =>
            {
                Title = "How";

                HowToPages.Clear();
                HowToPages.Add(new HowItemViewModel {
                    ImageText = "Simple", ImageSource = ImageSource.FromResource("DahlexApp.Assets.Screens.Screen1_1280.png")
                });
                HowToPages.Add(new HowItemViewModel {
                    ImageText = "Who is who", ImageSource = ImageSource.FromResource("DahlexApp.Assets.Screens.Screen2_1280.png")
                });
                HowToPages.Add(new HowItemViewModel {
                    ImageText = "Busy", ImageSource = ImageSource.FromResource("DahlexApp.Assets.Screens.Screen4_1280.png")
                });
            });
            //
        }
Ejemplo n.º 4
0
        private void StartWatcher()
        {
            Console.WriteLine("StartWatcher");

            _dispatcher.ExecuteOnMainThreadAsync(() =>
            {
                if (_locationWatcher.Started)
                {
                    Console.WriteLine("Watcher already started!");
                    return;
                }

                _locationWatcher.Start(new MvxLocationOptions()
                {
                    Accuracy = MvxLocationAccuracy.Coarse
                },
                                       location =>
                {
                    _locationWatcher.Stop();

                    OnSuccess(new MvxCoordinates()
                    {
                        Latitude  = location.Coordinates.Latitude,
                        Longitude = location.Coordinates.Longitude
                    });
                },
                                       error =>
                {
                    _locationWatcher.Stop();
                    Console.WriteLine(error.Code);
                    OnError(new Exception(error.Code.ToString()));
                });

                Task.Delay(_timeOut).ContinueWith(_ => OnTimeout());
            });
        }
Ejemplo n.º 5
0
 private async void Init()
 {
     await _dispatcher.ExecuteOnMainThreadAsync(() => { Database = Realm.GetInstance(); });
 }
Ejemplo n.º 6
0
        public async Task Sync()
        {
            try
            {
                _logger.Information(
                    $"{nameof(Sync)}: Started {(_startedManually ? "manually" : "automatically")}");

                bool isSyncServiceRunning = (_appSettings as IAndroidAppSettings)
                                            .GetBoolean(SyncBackgroundService.IsServiceRunningKey);

                if (!_startedManually && isSyncServiceRunning)
                {
                    _logger.Warning($"{nameof(Sync)}: The sync bg service is already running...");
                    return;
                }

                string msg = $"{_textProvider.Get("Syncing")}...";
                await _dispatcher.ExecuteOnMainThreadAsync(() => _messenger.Publish(new ShowProgressOverlayMsg(this, msg: msg)));

                if (!_networkService.IsInternetAvailable())
                {
                    _logger.Warning($"{nameof(Sync)}: Network is not available...");
                    msg = _textProvider.Get("NetworkNotAvailable");
                    await _dispatcher.ExecuteOnMainThreadAsync(() => _messenger.Publish(new ShowProgressOverlayMsg(this, false, msg)));

                    return;
                }

                bool syncOnlyOneTaskList = _taskListId.HasValue;
                if (syncOnlyOneTaskList)
                {
                    _logger.Information($"{nameof(Sync)}: We will perform a partial sync for the " +
                                        $"tasklistId = {_taskListId.Value} and its associated tasks");
                }
                else
                {
                    _logger.Information($"{nameof(Sync)}: We will perform a full sync");
                }

                var syncResults = !syncOnlyOneTaskList
                    ? await _syncService.PerformFullSync(true)
                    : await _syncService.PerformSyncOnlyOn(_taskListId.Value);

                if (syncResults.Any(r => !r.Succeed))
                {
                    var errors = string.Join(
                        $".{Environment.NewLine}",
                        syncResults
                        .Where(r => !r.Succeed)
                        .Select(r => r.Message)
                        .Distinct());

                    _logger.Error($"{nameof(Sync)}: Sync completed with errors = {errors}");
                }

                string message = syncResults.Any(r => !r.Succeed) ?
                                 _textProvider.Get("SyncUnknownError") :
                                 !_startedManually
                        ? _textProvider.Get("SyncAutoCompleted")
                        : _textProvider.Get("SyncManualCompleted");

                if (string.IsNullOrEmpty(message))
                {
                    message = "An unknown error occurred while trying to perform the sync operation.";
                }

                _logger.Information($"{nameof(Sync)}: results = {message}");
                await _dispatcher.ExecuteOnMainThreadAsync(() => _messenger.Publish(new ShowProgressOverlayMsg(this, false)));

                bool isInForeground = AndroidUtils.IsAppInForeground();
                if (!isInForeground && _appSettings.ShowToastNotificationAfterFullSync)
                {
                    _logger.Information($"{nameof(Sync)}: App is not in foreground, showing a notification...");
                    var notif = new TaskNotification
                    {
                        Content = message,
                        Title   = _textProvider.Get("SyncResults")
                    };
                    _notificationService.ShowNotification(notif);
                }
                else if (isInForeground)
                {
                    _logger.Information($"{nameof(Sync)}: App is in foreground, showing the snackbar msg...");
                    await _dispatcher.ExecuteOnMainThreadAsync(() =>
                    {
                        _dialogService.ShowSnackBar(message);
                        _messenger.Publish(new OnFullSyncMsg(this));
                    });
                }

                _logger.Information($"{nameof(Sync)}: completed successfully");
            }
            catch (Exception e)
            {
                _logger?.Error(e, $"{nameof(Sync)}: An unknown error occurred while trying to sync task / tasklists");
                _telemetryService?.TrackError(e);
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Takes the action on the main application's thread and executes it here
 /// </summary>
 /// <param name="action">The action to execute on main thread</param>
 /// <returns></returns>
 public async Task ExecuteOnMainThread(Action action)
 {
     await mMainThreadDispatcher.ExecuteOnMainThreadAsync(action);
 }