public void InvokeWithoutBlocking(SendOrPostCallback callback, object state)
        {
            ArgumentValidator.AssertNotNull(callback, "callback");
            EnsureInitialized();

            context.Post(callback, state);
        }
Exemplo n.º 2
0
        private void StartWork(UploadParam uploadParam)
        {
            try
            {
                Directory.SetCurrentDirectory(uploadParam.Directory);

                uploadParam.State = UploaderState.Processing;

                bool wasError = false;

                var dataLoader = DataLoaderFactory.CreateDataLoader(
                    uploadParam.Type, DataLoadingTarget, uploadParam.Name, uploadParam.OverwriteMode, uploadParam.SourceOrder);

                dataLoader.Load(
                    (totalCount, pocessedCount) => _synchronizationContext.Post(
                        state => { uploadParam.Progress = (int)(99 * (((float)pocessedCount) / totalCount)); }, null),
                    ex =>
                {
                    wasError = true;
                    _synchronizationContext.Post(
                        state =>
                    {
                        uploadParam.AppendMessageLine(ExceptionHelper.GetMessageStack(ex));
                        uploadParam.State = UploaderState.Errors;
                    }, null);
                });

                if (!wasError)
                {
                    uploadParam.State = UploaderState.Complete;
                }
            }
            catch (Exception ex)
            {
                _synchronizationContext.Post(
                    state =>
                {
                    uploadParam.State = UploaderState.Failed;
                    uploadParam.AppendMessageLine(ExceptionHelper.GetMessageStack(ex));
                }, null);
            }
            finally
            {
                _synchronizationContext.Post(
                    state =>
                {
                    uploadParam.Progress         = 100;
                    uploadParam.ProcessingStatus = ProcessingStatus.Processed;
                    _processingCount--;
                    RunNext();
                }, null);
            }
        }
Exemplo n.º 3
0
        public void InvokeAsynchronously(SendOrPostCallback callback, object state)
        {
            ArgumentHelper.AssertNotNull(callback, "callback");
            EnsureInitialized();

            _context.Post(callback, state);
        }
Exemplo n.º 4
0
        object RunOnUIThread(DispatcherOperationCallback dispatcherMethod, bool async)
        {
            if (Application.Current != null)
            {
                if (Application.Current.Dispatcher.Thread == Thread.CurrentThread)
                {
                    // This avoids dispatching to the UI thread if we are already in the UI thread.
                    // Without this runing a command like 1/0 was throwing due to nested dispatches.
                    return(dispatcherMethod.Invoke(null));
                }
            }

            Exception e                 = null;
            object    returnValue       = null;
            SynchronizationContext sync = new DispatcherSynchronizationContext(Dispatcher);

            if (sync == null)
            {
                return(null);
            }
            if (async)
            {
                sync.Post(
                    new SendOrPostCallback(delegate(object obj)
                {
                    try
                    {
                        returnValue = dispatcherMethod.Invoke(obj);
                    }
                    catch (Exception uiException)
                    {
                        e = uiException;
                    }
                }),
                    null);
            }
            else
            {
                sync.Send(
                    new SendOrPostCallback(delegate(object obj)
                {
                    try
                    {
                        returnValue = dispatcherMethod.Invoke(obj);
                    }
                    catch (Exception uiException)
                    {
                        e = uiException;
                    }
                }),
                    null);
            }

            if (e != null)
            {
                throw new System.Reflection.TargetInvocationException(e.Message, e);
            }
            return(returnValue);
        }
Exemplo n.º 5
0
        private string FetchWeatherFromServer()
        {
            // do stuff
            SendOrPostCallback callback = DoEvent;

            _requestingContext.Post(callback, "");
            _requestingContext = null;
            return("");
        }
Exemplo n.º 6
0
        // Called on an arbitrary thread.
        int NativeMethods.IHWEventHandler.HandleEvent(String pszDeviceID, String pszAltDeviceID, String pszEventType)
        {
            // Notify anyone who cares.
            lock (_TheLock)
            {
                if (_CancelAutoPlay != null)
                {
//                    String msg = String.Format("Rejected \"{0}\" AutoPlay event for device: {1}( {2} )", pszEventType, pszAltDeviceID, pszDeviceID);
                    CancelAutoPlayEventArgs args = new CancelAutoPlayEventArgs(pszDeviceID, pszAltDeviceID, pszEventType, 0);

                    // Post the message to the UI Thread.
                    _SynchronizationContext.Post(new SendOrPostCallback(_CancelAutoPlay), args);
                }
            }

            Trace.WriteLine(String.Format("*** DeviceManager.Instance.IHWEventHandler.HandleEvent(): Handled \"{0}\" AutoPlay event for device: {1}( {2} ), thread({3})", pszEventType, pszAltDeviceID, pszDeviceID, Thread.CurrentThread.GetHashCode()));
            return(NativeMethods.S_OK);
        }
Exemplo n.º 7
0
        public void InvokeAsynchronously(SendOrPostCallback callback, object state)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            EnsureInitialized();

            _context.Post(callback, state);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Report a mResult to the attached eventhalders (if any) on whether execution succeded or not.
        /// </summary>
        protected void ReportBatchResultEvent(bool bAsnc)
        {
            // non-Asnyc threads are simply blocked until they finish
            // hence completed event is not required to fire
            if (bAsnc == false)
            {
                return;
            }

            SendOrPostCallback callback = ReportTaskCompletedEvent;

            _mRequestingContext.Post(callback, null);
            _mRequestingContext = null;
        }
Exemplo n.º 9
0
        private string fetchWeatherFromServer()
        {
            // do stuff
            string weather = "";

            GetWeatherCompletedEventArgs e =
                new GetWeatherCompletedEventArgs(null, false, null, weather);

            SendOrPostCallback callback = new SendOrPostCallback(DoEvent);

            requestingContext.Post(callback, e);
            requestingContext = null;

            return(e.Weather);
        }
        public void Post()
        {
            DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext();
            // that would throw a NRE but we can't catch it
            //dsc.Post (null, this);

            bool complete = false;

            dsc.Post(delegate(object obj) {
                Assert.IsNull(obj, "Post");
                complete = true;
            }, null);

            EnqueueConditional(() => complete);
            EnqueueTestComplete();
        }
Exemplo n.º 11
0
        private void OnRecieve(IAsyncResult ar)
        {
            int nRecieved = m_socket.EndReceive(ar);

            Packet p = new Packet(buffer, nRecieved);

            m_packetQueue.Enqueue(p);

            //	Perform a Call back to the main thread os that it can process the data
            SendOrPostCallback callback = new SendOrPostCallback(ParseData);

            requestingContext.Post(callback, null);

            if (m_cancelled == false && m_socket != null)
            {
                buffer = new byte[4096];
                m_socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnRecieve), null);
            }
        }
Exemplo n.º 12
0
 protected override void QueueTask(Task task)
 {
     _synchronizationContext.Post(_postCallback, task);
 }
Exemplo n.º 13
0
 void ShowStatusAsync(string text, bool showProgress = false, double progress = double.NaN)
 {
     SyncContext.Post(ShowStatusCallback, new ShowStatusArgs(text, showProgress, progress));
 }
Exemplo n.º 14
0
 public void DispatchAsync(Action action)
 {
     _context.Post(state => action.Invoke(), null);
 }
Exemplo n.º 15
0
    void Start()
    {
        Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
        // flush just in case
        for (int i = 0; i < 100; i++)
        {
            ctx.Post(Callback, 9999999);
            this.Dispatcher.BeginInvoke(
                new Action <object>((object state) => { txt2.Text = state.ToString(); }),
                DispatcherPriority.Send, 9999999);
        }
        Thread.Sleep(1000);
        // results
        List <Tuple <long, long> > results = new List <Tuple <long, long> >();

        // actual test
        for (int x = 0; x < MACRO; x++)
        {
            Stopwatch sw = new Stopwatch();
            // sync context post
            long tick1, tick2;
            for (int i = 0; i < TESTS; i++)
            {
                sw.Start();
                for (int j = i; j < LOOPS + i; j++)
                {
                    ctx.Post(Callback, j);
                }
                sw.Stop();
                Thread.Sleep(1500);
            }
            tick1 = sw.ElapsedTicks;
            // begin invoke
            sw.Reset();
            for (int i = 0; i < TESTS; i++)
            {
                sw.Start();
                for (int j = i; j < LOOPS + i; j++)
                {
                    this.Dispatcher.BeginInvoke(
                        new Action <object>((object state) => { txt2.Text = state.ToString(); }),
                        DispatcherPriority.Normal, j);
                }
                sw.Stop();
                Thread.Sleep(1500);
            }
            tick2 = sw.ElapsedTicks;
            // store results
            results.Add(new Tuple <long, long>(tick1, tick2));
            // display to make it less boring
            this.Dispatcher.BeginInvoke(new Action(() => { txt3.Text += string.Format("{0} {1}. ", tick1, tick2); }));
            Thread.Sleep(100);
        }
        StringBuilder sb = new StringBuilder();

        foreach (var res in results)
        {
            sb.AppendLine(string.Format("{0}\t{1}\t{2:0.00}\t{3:0.0%}",
                                        res.Item1, res.Item2, (res.Item1 - res.Item2) / 10000, res.Item2 != 0 ? 1.0 - res.Item1 / (double)res.Item2 : 0.0));
        }
        this.Dispatcher.BeginInvoke(
            new Action(() => { txb1.Text = sb.ToString(); }));
    }