Пример #1
0
        private void SendAsync(bool showDlg)
        {
            if (IsSending)
            {
                throw new InvalidOperationException("ShowMailClient or Send has already been called.");
            }
            IsSending = true;

            var key     = new object();
            var asyncOp = AsyncOperationManager.CreateOperation(key);
            var t       = new Thread(SendAsyncWorker);

            t.SetApartmentState(ApartmentState.STA);
            t.Start(new SendAsyncThreadArgs()
            {
                ShowDialog = showDlg, Operation = asyncOp
            });
        }
Пример #2
0
        public void MyTaskAsync()
        {
            MyTaskWorkerDelegate worker            = new MyTaskWorkerDelegate(MyMouseWorker);
            AsyncCallback        completedCallback = new AsyncCallback(MyTaskCompletedCallback);

            lock (_sync)
            {
                if (_myTaskIsRunning)
                {
                    return;
                }
                //throw new InvalidOperationException("The control is currently busy.");

                AsyncOperation async = AsyncOperationManager.CreateOperation(null);
                worker.BeginInvoke(completedCallback, async);
                _myTaskIsRunning = true;
            }
        }
        /// <summary>
        /// Starts this EnityPoller.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Already polling</exception>
        public void Start()
        {
            var worker      = new AsyncWorker(Poll);
            var completed   = new AsyncCallback(PollComplete);
            var onCompleted = new AsyncComplete(OnEntity);

            lock (_sync)
            {
                if (_polling)
                {
                    throw new InvalidOperationException("Already polling");
                }

                var operation = AsyncOperationManager.CreateOperation(onCompleted);
                worker.BeginInvoke(completed, operation);
                _polling = true;
            }
        }
Пример #4
0
        /// <summary>
        /// Sends the service request async.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="state">The state.</param>
        public void SendServiceRequestAsync(IHttpCommand context, object state)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(state);

            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(state))
                {
                    throw new ArgumentException("state must be unique for async operation", "state");
                }

                userStateToLifetime[state] = asyncOp;
            }

            WorkerEventHandler workerDelegate = new WorkerEventHandler(SendServiceRequestAsyncWrapper);

            workerDelegate.BeginInvoke(context, asyncOp, null, null);
        }
Пример #5
0
        public static void GetOddNumbersAsync(int min, int max, object userState)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userState);

            lock (tasks.SyncRoot)
            {
                if (tasks.Contains(userState))
                {
                    throw new ArgumentException("The userState parameter must be unique!");
                }

                tasks[userState] = asyncOp;
            }

            GetWorkerOddNumbersHandler oddHandler = new GetWorkerOddNumbersHandler(OddNumbersWorker);

            oddHandler.BeginInvoke(min, max, asyncOp, null, null);
        }
Пример #6
0
        public virtual void GenerateAsync(GenerationParameter parameter, object taskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(taskId);

            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException("Task ID parameter must be unique", "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            WorkerEventHandler workerDelegate = new WorkerEventHandler(GenerateWorker);

            workerDelegate.BeginInvoke(parameter, asyncOp, null, null);
        }
Пример #7
0
        /// <summary>
        /// Asynchoronous version of the method
        /// </summary>
        /// <param name="message">just simple message to display</param>
        /// <param name="userState">Unique value to maintain the task</param>
        ///
        public void MathMulAsync(double[][] mat1, double[][] mat2, object userState)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userState);

            //Multiple threads will access the task dictionary, so it must be locked to serialze access
            lock (tasks.SyncRoot)
            {
                if (tasks.Contains(userState))
                {
                    throw new ArgumentException("User state parameter must be unique", "userState");
                }
                tasks[userState] = asyncOp;
            }
            WorkerEventHandler worker = new WorkerEventHandler(MathMulWorker);

            //Execute process Asynchronously
            worker.BeginInvoke(mat1, mat2, asyncOp, null, null);
        }
Пример #8
0
        public void ListTasksAsync(object userTaskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userTaskId);

            lock (taskListJobs.SyncRoot)
            {
                if (taskListJobs.Contains(userTaskId))
                {
                    throw new ArgumentException("Task ID parameter must be unique", "userTaskId");
                }
                taskListJobs[userTaskId] = asyncOp;
            }

            // Start the asynchronous operation.
            listTasksWorkerEventHandler workerDelegate = new listTasksWorkerEventHandler(listTasksWorker);

            workerDelegate.BeginInvoke(asyncOp, null, null);
        }
Пример #9
0
        public virtual void Run()
        {
            if (_operation != null)
            {
                throw new InvalidOperationException();
            }

            _operation = AsyncOperationManager.CreateOperation(null);
            Success    = true;
            if (AsyncRun)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(_ => InnerRun());
            }
            else
            {
                InnerRun();
            }
        }
Пример #10
0
        public ProcessesWatcher(RegionsManager regionsManager, SystemWindowsFactory windowsFactory, MoveWindowCommand moveWindowCommand)
        {
            _regionsManager    = regionsManager;
            _windowsFactory    = windowsFactory;
            _moveWindowCommand = moveWindowCommand;

            _asyncOperation = AsyncOperationManager.CreateOperation((object)null);
            _tickReporter   = new SendOrPostCallback(SyncedTick);

            SyncWindowsSet();

            _syncTimer = new Timer {
                Interval = 2000
            };
            _syncTimer.Elapsed  += SyncTick;
            _syncTimer.AutoReset = true;
            _syncTimer.Enabled   = true;
        }
Пример #11
0
        /// <summary>
        /// 开始操作
        /// </summary>
        void StartOperation()
        {
            if (WorkCallback == null && WorkCallbackAdvanced == null)
            {
                _completed = true;
                return;
            }

            if (AsyncWork)
            {
                _operation = AsyncOperationManager.CreateOperation(this);
                System.Threading.ThreadPool.QueueUserWorkItem(ThreadWorker);
            }
            else
            {
                ThreadWorker(null);
            }
        }
Пример #12
0
        private void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken)
        {
            if (string.IsNullOrEmpty(hostNameOrAddress))
            {
                throw new ArgumentNullException("hostNameOrAddress");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (buffer.Length > MaxBufferSize)
            {
                throw new ArgumentException(SR.net_invalidPingBufferSize, "buffer");
            }

            if (timeout < 0)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }

            IPAddress address;

            if (IPAddress.TryParse(hostNameOrAddress, out address))
            {
                SendAsync(address, timeout, buffer, options, userToken);
                return;
            }

            CheckStart(true);
            try
            {
                _cancelled = false;
                _asyncOp   = AsyncOperationManager.CreateOperation(userToken);
                AsyncStateObject state = new AsyncStateObject(hostNameOrAddress, buffer, timeout, options, userToken);
                ThreadPool.QueueUserWorkItem(new WaitCallback(ContinueAsyncSend), state);
            }
            catch (Exception e)
            {
                Finish(true);
                throw new PingException(SR.net_ping, e);
            }
        }
Пример #13
0
        public virtual void RequestStringAsync(
            EnumRequestMethod requestMethod,
            object taskId)
        {
            //HttpWebRequest requestObj = GetRequestObj(requestMethod);
            //RequestState requestState = new RequestState();
            //requestState.request = requestObj;
            //requestState.RequestId = taskId;
            //requestState.IsRequestString = true;
            //requestState.Context = SynchronizationContext.Current;
            //if (requestMethod == EnumRequestMethod.POST)
            //{
            //    requestState.PostData = this.PostData;
            //}
            //requestState.RequestMethod = requestMethod;
            //this.BeginHttpReqeust(requestState);
            // Create an AsyncOperation for taskId.

            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            WorkerEventHandler workerDelegate = new WorkerEventHandler(RequestStringWorker);

            workerDelegate.BeginInvoke(
                requestMethod,
                asyncOp,
                null,
                null);
        }
Пример #14
0
        /// <summary>
        /// Старт захвата параметров
        /// </summary>
        public void SensorStartLive()
        {
            //Если сейчас уже скан идет - остановим
            if (_flagIsScanning)
            {
                _flagIsScanning = false;
            }

            lock (this)
            {
                if (CountOfSensors == 0)
                {
                    throw new ConsultException("Нет доступных сенсоров, Сначала добавьте сенсор");
                }

                byte[] cmd = GetCommandToECU().ToArray();

                try
                {
                    _consult.SetClassState(ConsultClassState.ECU_STREAMING_MONITORS);

                    //Отправляю команду
                    _consult.SendCommand(cmd, ECUConst.ECU_REG_READ_CMD);

                    //старт приема данных
                    _consult.ECUFrameStart();

                    //Выставляем флаг начала сканирования
                    _flagIsScanning = true;

                    // Запускаем процедуру приема данных
                    // чтобы из рабочего потока можно было "присоединиться" к текущему потоку.
                    AsyncOperation ao = AsyncOperationManager.CreateOperation(null);
                    // запустить рабочий поток
                    new AsyncOperationInvoker(SensorLiveScanProcedure).BeginInvoke(ao, null, null);
                }
                catch (Exception ex)
                {
                    _consult.ECUFrameStop();
                    _consult.SetClassState(ConsultClassState.ECU_IDLE);
                    throw ex;
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Called to process the next queued work item.
        /// </summary>
        public void ProcessNextWorkRequest()
        {
            if (this.AllWorkersCompleted)
            {
                throw new AsyncWorkManagerException("Cannot restart an already completed queue manager.");
            }

            if (this.CancelRequested)
            {
                // Check to see that the cancelled request has not been processed
                if (!this.Cancelled)
                {
                    lock (this._lockObject)
                    {
                        if (!this.Cancelled)
                        {
                            CheckAndSendCancellationNotice();
                        }
                    }
                }
            }
            else if (this._workersQueue.Count > 0)
            {
                AsyncWorkRequest workRequest = this._workersQueue.Dequeue();

                AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(workRequest.Id);
                workRequest.SetAsyncOperation(asyncOp);

                ThreadPool.QueueUserWorkItem(new WaitCallback(
                                                 o =>
                {
                    asyncOp.SynchronizationContext.Post(new SendOrPostCallback(LaunchWorkerCallback), workRequest);
                }));
            }
            else
            {
                // No workers were found. End the session if no session is established or if a session has been
                // established and has completed.
                if (!this._sessionEnabled || (this._sessionEnabled && this._sessionCompleted))
                {
                    this.EndSession();
                }
            }
        }
        private void ViewOnShowLoggerBinImport(object sender, EventArgs eventArgs)
        {
            if (Project == null)
            {
                MessageBox.Show("Bitte zunächst ein Projekt erstellen oder öffnen.");
                return;
            }

            CommonOpenFileDialog loggerBinOpenFileDialog = new CommonOpenFileDialog {
                Multiselect = false
            };

            loggerBinOpenFileDialog.Filters.Add(
                new CommonFileDialogFilter("e-obs Binärdatei v7.2", "*.bin"
                                           ));

            CommonFileDialogResult dr = loggerBinOpenFileDialog.ShowDialog();

            if (dr != CommonFileDialogResult.Ok)
            {
                return;
            }

            const string DecoderBinaryFilename = "decoder_v7_2.exe";

            Process proc = new Process
            {
                StartInfo = new ProcessStartInfo(
                    Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location),
                                 DecoderBinaryFilename),
                    $"-f {loggerBinOpenFileDialog.FileName} -c m")
                {
                    CreateNoWindow   = false,
                    UseShellExecute  = true,
                    WindowStyle      = ProcessWindowStyle.Normal,
                    WorkingDirectory = Path.GetDirectoryName(loggerBinOpenFileDialog.FileName)
                },
                EnableRaisingEvents = true
            };

            proc.Exited += ProcOnExited;
            AsyncOp      = AsyncOperationManager.CreateOperation(null);
            proc.Start();
        }
Пример #17
0
        public void character_CalculationsInvalidated(object sender, EventArgs e)
        {
#if DEBUG
            DateTime start = DateTime.Now;
#endif
            this.Cursor = Cursors.Wait;
            if (asyncCalculation != null)
            {
                CharacterCalculationsBase oldCalcs = referenceCalculation;
                referenceCalculation = null;
                oldCalcs.CancelAsynchronousCharacterDisplayCalculation();
                asyncCalculation = null;
            }
            //_unsavedChanges = true;
            referenceCalculation = Calculations.GetCharacterCalculations(character, null, true, true, true);
            CalculationDisplay.SetCalculations(referenceCalculation.GetCharacterDisplayCalculationValues());
            UpdateDisplayCalculationValues(referenceCalculation.GetCharacterDisplayCalculationValues(), referenceCalculation);
            if (Character.PrimaryProfession == Profession.Blacksmithing || Character.SecondaryProfession == Profession.Blacksmithing)
            {
                //HandBSCheck.IsChecked = true;
                //WristBSCheck.IsChecked = true;
                HandBSCheck.IsEnabled  = true;
                WristBSCheck.IsEnabled = true;
            }
            else
            {
                HandBSCheck.IsChecked  = false;
                WristBSCheck.IsChecked = false;
                HandBSCheck.IsEnabled  = false;
                WristBSCheck.IsEnabled = false;
            }
            if (referenceCalculation.RequiresAsynchronousDisplayCalculation)
            {
                asyncCalculation = AsyncOperationManager.CreateOperation(null);
                ThreadPool.QueueUserWorkItem(delegate
                {
                    AsyncCalculationStart(referenceCalculation, asyncCalculation);
                });
            }
            this.Cursor = Cursors.Arrow;
#if DEBUG
            System.Diagnostics.Debug.WriteLine(string.Format("Finished MainPage CalculationsInvalidated: {0}ms", DateTime.Now.Subtract(start).TotalMilliseconds));
#endif
        }
Пример #18
0
        /// <summary>
        /// Called from the owner to start the worker
        /// </summary>
        /// <param name="asynchronous">
        /// Specifies if the worker must run in asynchronous mode (True) or not (False)
        /// </param>
        /// <remarks></remarks>
        public void StartWorker(bool asynchronous)
        {
            _isAsynchonous         = asynchronous;
            _cancelWorkerDoneEvent = false;

            if (_isAsynchonous)
            {
                //Asynchronous mode - we need to create a thread and start the worker using this thread
                _callingThreadAsyncOp      = AsyncOperationManager.CreateOperation(null);
                _workerThread              = new Thread(_worker.StartWorkerAsynchronous);
                _workerThread.IsBackground = true;
                _workerThread.Start();
            }
            else
            {
                //Synchronous mode - simply call the worker's start method
                _worker.StartWorkerSynchronous();
            }
        }
Пример #19
0
        /// <summary>
        /// Download file asynchronously
        /// Performs DownloadFileCompleted callback
        /// </summary>
        public void DownloadFileAsync(Task task, string outputPath, object userTaskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userTaskId);

            lock (downloadJobs.SyncRoot)
            {
                if (downloadJobs.Contains(userTaskId))
                {
                    throw new ArgumentException("Task ID parameter must be unique", "userTaskId");
                }
                downloadJobs[userTaskId] = asyncOp;
            }

            // Start the asynchronous operation.
            downloadWorkerEventHandler workerDelegate = new downloadWorkerEventHandler(downloadFileWorker);

            workerDelegate.BeginInvoke(task, outputPath, asyncOp,
                                       null, null);
        }
Пример #20
0
        private void MoveAsync(string name, string file, bool isBackup, Action <AsyncCompletedEventArgs> callback, object userState)
        {
            this.CheckInput(name, file, isBackup);

            AsyncOperation operation = AsyncOperationManager.CreateOperation(userState);
            SqlCommand     command   = this.CreateCommand(name, file, isBackup);

            command.BeginExecuteNonQuery((ar) => {
                Exception error = null;
                try {
                    command.EndExecuteNonQuery(ar);
                } catch (Exception ex) {
                    error = ex;
                } finally {
                    this.Clean(command.Connection, command);
                    operation.PostOperationCompleted((state) => callback(new AsyncCompletedEventArgs(error, false, state)), operation.UserSuppliedState);
                }
            }, null);
        }
Пример #21
0
            public virtual void MatMulAsync(double[] mat1, double[] mat2, int size, object taskId)
            {
                AsyncOperation asyncOp =
                    AsyncOperationManager.CreateOperation(taskId);

                lock (tasks.SyncRoot)
                {
                    if (tasks.Contains(taskId))
                    {
                        throw new ArgumentException(
                                  "Task ID parameter must be unique",
                                  "taskId");
                    }
                    tasks[taskId] = asyncOp;
                }
                WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);

                workerDelegate.BeginInvoke(mat1, mat2, size, asyncOp, null, null);
            }
Пример #22
0
        public void DownloadAsync(object userState)
        {
            lock (asyncOpLock) {
                if (asyncOp != null)
                {
                    throw new InvalidOperationException("Another async operation in progress.");
                }
                asyncOp = AsyncOperationManager.CreateOperation(userState);
            }

            Contract.Requires(cancellationTokenSource == null);

            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken       = cancellationTokenSource.Token;
            IsBusy = true;

            // Is Task.Dispose() required?
            taskFactory.StartNew(DownloadTaskStart, asyncOp);
        }
Пример #23
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            MyTcpClient client = MyTcpClient.getInstance();

            //保证回调函数是在创建他的上下文执行(一般是UI线程)
            client.AsyncOperation = AsyncOperationManager.CreateOperation(null);

            /*
             * client.Error += Client_Error; ;
             * client.Receive += Client_Receive; ;
             * client.Connected += Client_Connected;
             */
            client.Connect();

            comboDeadZone.Items.AddRange(Enum.GetNames(typeof(GamePadDeadZone)));
            comboDeadZone.SelectedItem = reporterState.DeadZone.ToString();

            pollingWorker.RunWorkerAsync();
        }
Пример #24
0
        public void LongTaskAsync(string input, object taskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(taskId);

            lock (userStateDictionary)
            {
                if (userStateDictionary.ContainsKey(taskId))
                {
                    throw new ArgumentException("taskId must be unique", "taskId");
                }


                userStateDictionary[taskId] = asyncOp;
            }

            LongTaskWorkHandler someLongTaskDelegate = DoLongTask;

            someLongTaskDelegate.BeginInvoke(input, asyncOp, null, null);
        }
 private void AsynOperationCompleted(object args)
 {
     lock (statusChangeLockObject)
     {
         isWorking = false;
         if (!enabled)
         {
             isRunning = false;
             try
             {
                 mainThreadOperation.OperationCompleted();
             }
             catch { }
         }
     }
     OnRunWorkerCompleted((RunWorkerCompletedEventArgs)args);
     workThreadOperation = AsyncOperationManager.CreateOperation(null);
     workThreadOperation.PostOperationCompleted(completedCallback, null);
 }
Пример #26
0
        /// <summary>
        /// 开始异步操作
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        protected AsyncOperation BeginAsync(object taskId)
        {
            // Create an AsyncOperation for taskId.
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (_taskIdToLifetime.SyncRoot)
            {
                if (_taskIdToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }
                _taskIdToLifetime[taskId] = asyncOp;
            }
            return(asyncOp);
        }
        /// <include file='doc\SoapClientProtocol.uex' path='docs/doc[@for="SoapClientProtocol.InvokeAsync1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected void InvokeAsync(string methodName, object[] parameters, SendOrPostCallback callback, object userState)
        {
            if (userState == null)
            {
                userState = NullToken;
            }
            InvokeAsyncState     invokeState = new InvokeAsyncState(methodName, parameters);
            AsyncOperation       asyncOp     = AsyncOperationManager.CreateOperation(new UserToken(callback, userState));
            WebClientAsyncResult asyncResult = new WebClientAsyncResult(this, invokeState, null, new AsyncCallback(InvokeAsyncCallback), asyncOp);

            try {
                AsyncInvokes.Add(userState, asyncResult);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                {
                    throw;
                }
                if (Tracing.On)
                {
                    Tracing.ExceptionCatch(TraceEventType.Warning, this, "InvokeAsync", e);
                }
                Exception exception = new ArgumentException(Res.GetString(Res.AsyncDuplicateUserState), e);
                InvokeCompletedEventArgs eventArgs = new InvokeCompletedEventArgs(new object[] { null }, exception, false, userState);
                asyncOp.PostOperationCompleted(callback, eventArgs);
                return;
            }
            try {
                BeginSend(Uri, asyncResult, true);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                {
                    throw;
                }
                if (Tracing.On)
                {
                    Tracing.ExceptionCatch(TraceEventType.Warning, this, "InvokeAsync", e);
                }
                OperationCompleted(userState, new object[] { null }, e, false);
            }
        }
Пример #28
0
        /// <summary>
        /// Method to udpate Writeback status for a given WR. This method will be called by client asyncronously. Client needs to register the event WriteBackProcessCompleted to get the notification of method completion
        /// </summary>
        /// <param name="p_wrNumber">WR number</param>
        /// <param name="taskId"></param>

        public void UpdateWriteBack(string p_wrNumber, object taskId)
        {
            string sJobIdentifier = string.Empty;

            this.cc = new ConfirmComplete();
            this.WriteBackProcessCompleted += WritebackClass_WriteBackProcessCompleted;
            this.cc.enableOK   = false;
            this.cc.statusText = "Writing data to WMIS...";
            this.cc.SetDesktopLocation(0, 0);
            this.cc.Show(m_oApp.ApplicationWindow);
            this.cc.TopMost = true;
            this.cc.Text    = "WR# " + p_wrNumber;


            // When the cc form closes, dispose of it properly.
            this.cc.FormClosed += Cc_FormClosed;

            InitializeWriteBackDelegates();
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(taskId);

            string sUserName       = m_oApp.DataContext.DatabaseUserName;
            string sPasswordString = m_oApp.DataContext.ViewerConnectionString.Substring(m_oApp.DataContext.ViewerConnectionString.IndexOf("Password="******"Password="******"Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }
            WorkerEventHandler workerDelegate = new WorkerEventHandler(UpdateWritebackStatusWorker);

            workerDelegate.BeginInvoke(
                p_wrNumber,
                asyncOp, sUserName, sPasswordString,
                null, null
                );
        }
Пример #29
0
        public void Execute(IServiceMethodUiBridge serviceMethodUiBridge)
        {
            m_ServiceMethodUiBridge = serviceMethodUiBridge;
            AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(m_AsyncKey);

            try
            {
                FeatureKey featureKey = BuildFeatureKey(serviceMethodUiBridge);

                UpdateFeatureStateRequest request = UpdateFeatureStateRequest.Create(
                    MessageIdFactory.GenerateMessageId(),
                    featureKey,
                    serviceMethodUiBridge.FeatureStoreMethodArguments.State);

                IFeatureStoreServiceProxy featureStoreServiceProxy = new FeatureStoreServiceProxy();

                featureStoreServiceProxy.BeginUpdateFeatureState(
                    request,
                    ar =>
                {
                    string rtfResults;
                    try
                    {
                        UpdateFeatureStateResponse response =
                            featureStoreServiceProxy.EndUpdateFeatureState(ar);

                        rtfResults = BuildResultsRichText(request, response, GetType().Name);
                    }
                    catch (Exception e)
                    {
                        rtfResults = BuildExceptionRichText(e);
                    }

                    asyncOperation.PostOperationCompleted(HandleEndAsync, rtfResults);
                },
                    null);
            }
            catch (Exception e)
            {
                serviceMethodUiBridge.DisplayResults(BuildExceptionRichText(e));
            }
        }
Пример #30
0
        // WARNING: Any changes in the signature/name of the following method ctor must be applied to the
        // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
        protected void InvokeAsync(BeginOperationDelegate beginOperationDelegate, object[] inValues,
                                   EndOperationDelegate endOperationDelegate, SendOrPostCallback operationCompletedCallback, object userState)
        {
            if (beginOperationDelegate == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(beginOperationDelegate));
            }
            if (endOperationDelegate == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endOperationDelegate));
            }

            AsyncOperation        asyncOperation = AsyncOperationManager.CreateOperation(userState);
            AsyncOperationContext context        = new AsyncOperationContext(asyncOperation, endOperationDelegate, operationCompletedCallback);

            Exception error = null;

            object[]     results = null;
            IAsyncResult result  = null;

            try
            {
                result = beginOperationDelegate(inValues, s_onAsyncCallCompleted, context);
                if (result.CompletedSynchronously)
                {
                    results = endOperationDelegate(result);
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                error = e;
            }

            if (error != null || result.CompletedSynchronously) /* result cannot be null if error == null */
            {
                CompleteAsyncCall(context, results, error);
            }
        }