RunAsync() public method

public RunAsync ( [ priority, [ agileCallback ) : IAsyncAction
priority [
agileCallback [
return IAsyncAction
示例#1
1
        public static async void ExecuteAsync(CoreDispatcher dispatcher)
        {
            var task = dispatcher.RunAsync(CoreDispatcherPriority.High, ()
                 => CmdGo.Instance.Execute(null));

            //TaskScheduler.Current
            await task;
        }
示例#2
1
        private async void ConnectToWifi(WiFiAvailableNetwork network, PasswordCredential credential, CoreDispatcher dispatcher)
        {
            var didConnect = credential == null ?
                networkPresenter.ConnectToNetwork(network, Automatic) :
                networkPresenter.ConnectToNetworkWithPassword(network, Automatic, credential);

            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                SwitchToItemState(network, WifiConnectingState, false);
            });

            if (await didConnect)
            {
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    NavigationUtils.NavigateToScreen(typeof(MainPage));
                });
            }
            else
            {
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var item = SwitchToItemState(network, WifiInitialState, false);
                    item.IsSelected = false;
                });
            }
        }
示例#3
0
    async void RenderSocialGroupList(List <XboxSocialUserGroup> socialUserGroups)
    {
        Windows.UI.Core.CoreDispatcher UIDispatcher = Windows.UI.Xaml.Window.Current.CoreWindow.Dispatcher;
        await UIDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                    () =>
        {
            m_ui.ClearSocialGroup();

            foreach (XboxSocialUserGroup socialUserGroup in socialUserGroups)
            {
                m_ui.AppendToSocialGroup("--------------------");
                if (socialUserGroup.SocialUserGroupType == SocialUserGroupType.FilterType)
                {
                    m_ui.AppendToSocialGroup(
                        string.Format("Group from filter: {0} {1}", socialUserGroup.PresenceFilterOfGroup.ToString(), socialUserGroup.RelationshipFilterOfGroup.ToString())
                        );
                }
                else
                {
                    m_ui.AppendToSocialGroup("Group from custom list");
                }

                IReadOnlyList <XboxSocialUser> userList = socialUserGroup.Users;
                foreach (XboxSocialUser socialUser in userList)
                {
                    m_ui.AppendToSocialGroup("Gamertag: " + socialUser.Gamertag + ". Status: " + socialUser.PresenceRecord.UserState.ToString());
                }

                if (userList.Count == 0)
                {
                    m_ui.AppendToSocialGroup("No friends found");
                }
            }
        });
    }
 private async void OnTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     await m_coreDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         //rootPage.NotifyUser("Background task completed", NotifyType.StatusMessage);
     });
 }
示例#5
0
        private void Output(string format, params object[] args)
        {
            var message = string.Format(format, args);

            _dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                 () => { _output.Text = _output.Text + "\n" + message; }).AsTask().Wait();
        }
示例#6
0
        public void Invoke(Action action)
        {
            var ev = new ManualResetEvent(false);

            dispatcher.RunAsync(wuc.CoreDispatcherPriority.Normal, () => {
                try
                {
                    action();
                }
                finally
                {
                    ev.Set();
                }
            });

            ev.WaitOne();
        }
示例#7
0
        public void Invoke(Action action)
        {
            var ev = new ManualResetEvent(false);

#pragma warning disable 4014
            dispatcher.RunAsync(wuc.CoreDispatcherPriority.Normal, () => {
                try
                {
                    action();
                }
                finally
                {
                    ev.Set();
                }
            });
#pragma warning restore 4014
            ev.WaitOne();
        }
        /// <summary>
        /// Forwards the BeginInvoke to the current application's <see cref="Dispatcher"/>.
        /// </summary>
        /// <param name="method">Method to be invoked.</param>
        /// <param name="arg">Arguments to pass to the invoked method.</param>
        public Task BeginInvoke(Delegate method, params object[] arg)
        {
            if (dispatcher != null)
                return dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => method.DynamicInvoke(arg)).AsTask();

            var coreWindow = CoreApplication.MainView.CoreWindow;
            if (coreWindow != null)
            {
                dispatcher = coreWindow.Dispatcher;
                return dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => method.DynamicInvoke(arg)).AsTask();
            }
            else
                return Task.Delay(0);
        }
 public async Task<ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource,
     IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource)
 {
     _bitmapImage = new BitmapImage();
     await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         var uri = image.Tag as Uri;
         if (uri == uriSource)
         {
             image.Source = _bitmapImage;
         }
     });
     await _bitmapImage.SetSourceAsync(streamSource).AsTask(cancellationTokenSource.Token);
     return new ImagePackage(this, _bitmapImage, _bitmapImage.PixelWidth, _bitmapImage.PixelHeight);
 }
示例#10
0
        private async void SoundEffect()
        {
            this.mediaPlayerAudio.SetMediaPlayer(_mediaPlayer);
            this.mediaPlayerAudio.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Danzon_De_Pasion_Sting.mp3"));
            this._mediaPlayer            = mediaPlayerAudio.MediaPlayer;
            this._mediaPlayer.Volume     = 1f;



            await messageDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                             () =>

            {
                this._mediaPlayer.Play();
            });
        }
 public static void SearchForUsbDevices(CoreDispatcher dispatcher)
 {
     DeviceWatcher deviceWatcher =
         DeviceInformation.CreateWatcher(HidDevice.GetDeviceSelector(uPage, uid));
     deviceWatcher.Added += (s, a) => dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
     {
         HidDevice hidDevice = await HidDevice.FromIdAsync(a.Id, FileAccessMode.ReadWrite);
         var launcher = new ProgrammatorDevice(hidDevice);
         if (UsbDeviceFound != null)
         {
             UsbDeviceFound(null, new ProgrammatorDeviceEventArgs(launcher));
         }
           
         deviceWatcher.Stop();
     });
     deviceWatcher.Start();
 }
示例#12
0
        /// <summary>
        /// Display a dialog box with a custom action when the user presses "OK"
        /// </summary>
        /// <param name="dispatcher">UI thread's dispatcher</param>
        /// <param name="content">Message box content</param>
        /// <param name="title">Message box title</param>
        /// <param name="okHandler">Callback executed when the user presses "OK"</param>
        public static void DisplayDialog(CoreDispatcher dispatcher, string content, string title, UICommandInvokedHandler okHandler)
        {
            Debug.WriteLine("Dialog requested: " + title + " - " + content);

            var unused = dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                var dialog = new MessageDialog(content, title);

                if (okHandler != null)
                {
                    dialog.Commands.Add(new UICommand("OK", okHandler));
                }
                else
                {
                    dialog.Commands.Add(new UICommand("OK"));
                }

                dialog.DefaultCommandIndex = 0;
                dialog.CancelCommandIndex = 0;

                await dialog.ShowAsync();
            });
        }
示例#13
0
 public async Task<ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource,
     IRandomAccessStream streamSource,
      CancellationTokenSource cancellationTokenSource)
 {
     byte[] bytes = new byte[streamSource.Size];
     await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token);
     int width, height;
     WriteableBitmap writeableBitmap = null;
     if (WebpCodec.GetInfo(bytes, out width, out height))
     {
         writeableBitmap = new WriteableBitmap(width, height);
         await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
          {
              var uri = image.Tag as Uri;
              if (uri == uriSource)
              {
                  image.Source = writeableBitmap;
              }
          });
         WebpCodec.Decode(writeableBitmap, bytes);
     }
     return new ImagePackage(this, writeableBitmap, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight);
 }
示例#14
0
 public static void BeginInvoke(this CoreDispatcher dispatcher, Action action)
 {
     dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action()).AsTask().Forget();
 }
示例#15
0
        private static void InvokeSync(CoreDispatcher dispatcher, Action action)
        {
            Exception exception = null;

            // TODO Research dispatcher.RunIdleAsync
            dispatcher.RunAsync(
                CoreDispatcherPriority.Normal, 
                () =>
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception ex)
                        {
                            exception = ex;
                        }
                    }).AsTask().Wait();

            if (exception != null)
            {
                throw exception;
            }
        }
示例#16
0
        public async Task<ImageSource> InitializeAsync(CoreDispatcher dispatcher,
            IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource)
        {

            var inMemoryStream = new InMemoryRandomAccessStream();
            var copyAction = RandomAccessStream.CopyAndCloseAsync(
                           streamSource.GetInputStreamAt(0L),
                           inMemoryStream.GetOutputStreamAt(0L));
            await copyAction.AsTask(cancellationTokenSource.Token);

            var bitmapDecoder = await BitmapDecoder.
                CreateAsync(BitmapDecoder.GifDecoderId, inMemoryStream).AsTask(cancellationTokenSource.Token).ConfigureAwait(false);
            var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);
            var frameProperties = new List<FrameProperties>();
            for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
            {
                var bitmapFrame = await bitmapDecoder.GetFrameAsync(i).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); ;
                frameProperties.Add(await RetrieveFramePropertiesAsync(i, bitmapFrame));
            }

            _frameProperties = frameProperties;
            _bitmapDecoder = bitmapDecoder;
            _imageProperties = imageProperties;
            _dispatcher = dispatcher;

            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 CreateCanvasResources();
             });

            _isInitialized = true;
            return _canvasImageSource;
        }
 public static void ExecuteOnUIThread(Action action, CoreDispatcher dispatcher)
 {
     if (dispatcher.HasThreadAccess)
         action();
     else
     {
         var asyncaction = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
     }
 }
示例#18
0
        public async void Execute(CoreDispatcher dispatcher)
        {
            // TODO: Implement a cancellation token to allow for a task cancellation
            // when the app is closed or put in sleep mode
            var RootFilter = new HttpBaseProtocolFilter();
            RootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
            RootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

            dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(this.BaseUrl);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    string json_object = "webservice.php?";

                    if (this._parameters.Count > 0)
                    {
                        foreach (KeyValuePair<string, string> param in this._parameters)
                        {

                            json_object += string.Format("{0}={1}&", param.Key, param.Value);
                        }
                    }

                    HttpResponseMessage response = httpClient.GetAsync(json_object).Result;
                    string statusCode = response.StatusCode.ToString();
                    response.EnsureSuccessStatusCode();

                    Task<string> responseBody = response.Content.ReadAsStringAsync();

                    this.BaseUrl = "http://66.90.73.236/bgconvention/webservice.php";

                    _callback(new ApiResponse(responseBody.Result));

                }

            });

        }
示例#19
0
        public async Task<ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource,
            IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource)
        {
   
            var bitmapDecoder = ImagingCache.Get<BitmapDecoder>(uriSource);
            if (bitmapDecoder == null)
            {
                var inMemoryStream = new InMemoryRandomAccessStream();
                var copyAction = RandomAccessStream.CopyAndCloseAsync(
                               streamSource.GetInputStreamAt(0L),
                               inMemoryStream.GetOutputStreamAt(0L));
                await copyAction.AsTask(cancellationTokenSource.Token);
                bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, inMemoryStream);
                ImagingCache.Add(uriSource, bitmapDecoder);
            }

            var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);
            var frameProperties = new List<FrameProperties>();

            for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
            {
                var bitmapFrame = await bitmapDecoder.GetFrameAsync(i).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); ;
                frameProperties.Add(await RetrieveFramePropertiesAsync(i, bitmapFrame));
            }

            _frameProperties = frameProperties;
            _bitmapDecoder = bitmapDecoder;
            _imageProperties = imageProperties;
            _dispatcher = dispatcher;

            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 CreateCanvasResources();
                 var uri = image.Tag as Uri;
                 if (uri == uriSource)
                 {
                     image.Source = _canvasImageSource;
                 }
             });

            _isInitialized = true;
            return new ImagePackage(this, _canvasImageSource, _imageProperties.PixelWidth, _imageProperties.PixelHeight); ;
        }
示例#20
0
 protected override void WriteLine(string message)
 {
     _dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                          () => { _output.Text = _output.Text + "\n" + message; }).AsTask().Wait();
 }
示例#21
0
 public override void Post(SendOrPostCallback d, object state)
 {
     _dispatcher.RunAsync(_priority, () => d(state));
 }
示例#22
0
 public static void runInForeground(CoreDispatcher Dispatcher, Action actionToRun)
 {
     if (Dispatcher != null)
         Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => actionToRun());
     else
         Windows.System.Threading.ThreadPool.RunAsync(handler => actionToRun());
 }
 private static async void beginCore(CoreDispatcher dispatcher, CoreDispatcherPriority priority, DispatchedHandler agileCallback)
 {
     await dispatcher.RunAsync(priority, agileCallback);
 }
示例#24
0
        private async void ConnectToWifi(WiFiAvailableNetwork network, PasswordCredential credential, CoreDispatcher dispatcher)
        {
            var didConnect = credential == null ?
                networkPresenter.ConnectToNetwork(network, Automatic) :
                networkPresenter.ConnectToNetworkWithPassword(network, Automatic, credential);

            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                SwitchToItemState(network, WifiConnectingState, false);
            });

            DataTemplate nextState = (await didConnect) ? WifiConnectedState : WifiInitialState;

            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var item = SwitchToItemState(network, nextState, false);
                item.IsSelected = false; 
            });
        }
示例#25
0
		private static async Task RunInUiThreadAsync(CoreDispatcher dispatcher, DispatchedHandler action)
		{
			if (dispatcher.HasThreadAccess)
			{
				action();
			}
			else
			{
				await dispatcher.RunAsync(CoreDispatcherPriority.Normal, action).AsTask().ConfigureAwait(false);
			}
		}
示例#26
0
        internal void Run(IAsyncAction action, CoreDispatcher uiDispatcher)
        {
            bool cont = true;
            AppTaskResult? lastResult = null;
            while (cont)
            {
                var task = TaskStack.Pop();
                object data;
                bool success = task(Parameter, action, lastResult, out data);
                lastResult = new AppTaskResult(success, data, lastResult);
                cont = (SuccessFallbackLimit == -1 || SuccessFallbackLimit > CurrentLevel) && TaskStack.Count > 0;
                CurrentLevel++;
            }
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            if (action.Status != AsyncStatus.Canceled)
                uiDispatcher.RunAsync(CoreDispatcherPriority.High, () => { CompletedCallback(lastResult.Value); });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
        }
示例#27
0
        private async void EnsureInitialized(Frame frame, IActivatedEventArgs args)
        {
            //
            // Do not repeat app initialization when already running, just ensure that
            // the window is active
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Window.Current.Activate();
                return;
            }

            //
            // create application
            //
            ApplicationModel.Current.AllCours.CollectionChanged += (sender, ncce) =>
            {
                //
                // update tiles
                //
                UpdateTileNotifications();
            };
            //
            // hook up
            //
            SearchPane.GetForCurrentView().QuerySubmitted += App_QuerySubmitted;
            //
            // set frame
            //
            RootFrame = frame;
            //
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            //
            if (RootFrame == null)
            {
                //
                // Create a Frame to act as the navigation context and navigate to the first page
                //
                RootFrame = new CharmFrame { CharmContent = new Settings.Settings() };
                //
                //Associate the frame with a SuspensionManager key                                
                //
                SuspensionManager.RegisterFrame(RootFrame, "AppFrame");
                //
                // look at previous state
                //
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated || args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
                {
                    //
                    // Restore the saved session state only when appropriate
                    //
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                        //
                        // sync
                        //
                        //ApplicationModel.Current.Synchronize();
                    }
                    catch (SuspensionManagerException)
                    {
                        //
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                        //
                    }
                }
                //
                // Place the frame in the current Window
                //
                Window.Current.Content = RootFrame;
                //
                // set dispatcher
                //
                CoreDispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
                //
                // get the ConnectionProfile that is currently used to connect to the Internet                
                //
                NetworkInformation.NetworkStatusChanged += async (sender) =>
                {
                    //
                    // get the ConnectionProfile that is currently used to connect to the Internet                
                    //
                    bool connected = NetworkInformation.GetInternetConnectionProfile() != null;
                    //
                    // dispatch on UI thread
                    //
                    await CoreDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        //
                        // update
                        //
                        ApplicationModel.Current.IsConnected = connected;
                    });
                };
            }
            if (RootFrame.Content == null)
            {
                //
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                //
                if (!RootFrame.Navigate(typeof(HomePage), null))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            //
            // Ensure the current window is active
            //
            Window.Current.Activate();
            //
            // load state
            //
            ApplicationModel.Current.LoadState();
            //
            // load settings
            //
            ApplicationModel.Current.LoadPersistentSettings();
            //
            // synchronize
            //
            ApplicationModel.Current.Synchronize();
        }
示例#28
-14
        public async static Task InvokeOnUI(CoreDispatcher d, Action a)
#endif
        {
#if WINDOWS_PHONE 
            d.BeginInvoke(a);
            await Task.Delay(0);
#elif !NETFX_CORE
            await d.BeginInvoke(a);
#else
            await d.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(a));
#endif
        }