EndInvoke() private method

private EndInvoke ( IAsyncResult asyncResult ) : object
asyncResult IAsyncResult
return object
		/// <summary>
		/// Shows standard decryption error UI within the context of a parent form
		/// </summary>
		public static DecryptionErrorAction OnDecryptionError(Control form, IContentEncryption encryptor)
		{
			if (form.InvokeRequired)
			{
				DecryptionErrorAction result = DecryptionErrorAction.Skip;
				IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
				{
					result = ShowDecryptionErrorDialog(form, encryptor);
				}));
				form.EndInvoke(async);
				return result;
			}
			return ShowDecryptionErrorDialog(form, encryptor);
		}
		/// <summary>
		/// Shows standard content encryption UI
		/// </summary>
		public static DecryptResult GetPassword(Control form, string attachmentName, string passwordName, string passwordDescription, out string password)
		{
			if (form.InvokeRequired)
			{
				DecryptResult result = DecryptResult.Ok;
				string pwd = string.Empty;
				IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
				{
					result = ShowPasswordRequestDialog(form, attachmentName, passwordName, passwordDescription, out pwd);
				}));
				form.EndInvoke(async);
				password = pwd;
				return result;
			}
			return ShowPasswordRequestDialog(form, attachmentName, passwordName, passwordDescription, out password);
		}
        /// <summary>
        /// Shows standard content encryption UI
        /// </summary>
        public static DecryptResult GetPasswords(Control form, string attachmentName, string attachmentDisplayName, out string openPassword, out string modifyPassword)
        {
            if (form.InvokeRequired)
            {
                DecryptResult result = DecryptResult.Ok;
                string pwdOpen = string.Empty;
                string pwdModify = string.Empty;

                IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
                {
                    result = ShowExtendedPasswordRequestDialog(form, attachmentName, attachmentDisplayName, out pwdOpen, out pwdModify);
                }));
                form.EndInvoke(async);

                openPassword = pwdOpen;
                modifyPassword = pwdModify;

                return result;
            }

            return ShowExtendedPasswordRequestDialog(form, attachmentName, attachmentDisplayName, out openPassword, out modifyPassword);
        }
Example #4
0
        private unsafe void PeakMessage(Message *ptrMessage, int messageNumber)
        {
            //must be first message
            if (messageNumber != 1)
            {
                throw new Exception("PeakMessage must be the first message");
            }

            // p1  = handle
            IntPtr handle    = GetParameterIntPtr(ptrMessage, 0);
            int    timeoutMS = GetParameterInt32(ptrMessage, 1);

            int threadId = NM.GetWindowThreadProcessId(handle, out int pid);

            m_AllControls = new List <IntPtr>();
            NM.EnumThreadWindows((uint)threadId, EnumThreadProcedue, IntPtr.Zero);

            Stopwatch timer = Stopwatch.StartNew();

            for (int loop = 0; loop < 2; loop++)
            {
                foreach (IntPtr hWnd in m_AllControls)
                {
                    WF.Control control = WF.Control.FromHandle(hWnd);

                    if (control == null)
                    {
                        //Todo
                    }
                    else
                    {
                        while (true)
                        {
                            bool messageAvailble = false;
                            if (control.IsDisposed)
                            {
                                // Nothing
                            }
                            else if (control.Disposing)
                            {
                                messageAvailble = true; // Don't invoke anything just continue to loop till the control is fully disposed
                            }
                            else if (!control.IsHandleCreated)
                            {
                                // Nothing as to get to here the handle must have existed at some point so it must have been destroyed
                            }
                            else if (control.RecreatingHandle)
                            {
                                messageAvailble = true; // Don't invoke anything just continue to loop till the control has recreated the handle
                            }
                            else if (!control.Enabled)
                            {
                                // Nothing move on to the next window
                            }
                            else
                            {
                                try
                                {
                                    //control.BeginInvoke(m_RefreshControlDelegater, new object[] { control });
                                    IAsyncResult result = control.BeginInvoke(m_PeakMessagDelegater, null);
                                    while (true)
                                    {
                                        int innerLoop = 0;
                                        if (result.IsCompleted)
                                        {
                                            messageAvailble = (bool)control.EndInvoke(result);
                                            break;
                                        }

                                        if (control.IsDisposed)
                                        {
                                            // Nothing
                                            break;
                                        }
                                        else if (control.Disposing)
                                        {
                                            // Don't do anything just continue to loop till the control is fully disposed
                                        }
                                        else if (!control.IsHandleCreated)
                                        {
                                            // Nothing as to get to here the handle must have existed at some point so it must have been destroyed
                                            break;
                                        }
                                        else if (control.RecreatingHandle)
                                        {
                                            messageAvailble = true; // Don't invoke anything just continue to loop till the control has recreated the handle
                                            break;
                                        }
                                        else if (!control.Enabled)
                                        {
                                            // Nothing move on to the next window
                                            break;
                                        }

                                        if (timer.ElapsedMilliseconds > timeoutMS)
                                        {
                                            throw new Exception("Thread failed to have zero messages within timeout");
                                        }

                                        innerLoop++;

                                        if (innerLoop == 100)
                                        {
                                            innerLoop = 0;
                                            Thread.Sleep(15);
                                        }
                                        else
                                        {
                                            Thread.Yield();
                                        }
                                    }
                                }
                                catch (ObjectDisposedException) { }
                                catch (InvalidAsynchronousStateException) { }
                                catch (NullReferenceException) { }
                                catch (InvalidOperationException) { }
                            }

                            if (!messageAvailble)
                            {
                                break;
                            }

                            if (timer.ElapsedMilliseconds > timeoutMS)
                            {
                                throw new Exception("Thread failed to have zero messages within timeout");
                            }

                            Thread.Sleep(15);
                        }
                        break;
                    }
                }
            }

            CleanUpMessage(ptrMessage);
        }
		/// <summary>
		/// Shows content encryption UI
		/// </summary>
		public static DecryptResult GetPasswords(Control form, string attachmentName, string attachmentDisplayName, Dictionary<string, string> passwords, PropertyChangedEventHandler callback)
		{
			if (form.InvokeRequired)
			{
				DecryptResult result = DecryptResult.Ok;
				
				IAsyncResult async = form.BeginInvoke(new MethodInvoker(delegate
					{
						ContentEncryptionDialog dlg = new ContentEncryptionDialog(attachmentName, callback, passwords.Keys.ToList());
						if (dlg.ShowDialog() != DialogResult.OK)
							result = DecryptResult.Cancel;
					}));
				form.EndInvoke(async);
				
				return result;
			}
			return DecryptResult.Ok;
		}
 /// <summary>
 /// Attempts to execute the specified action on the thread that owns the specified control, if the control is in a valid state.
 /// </summary>
 /// <param name="control">The control in whose thread context the specified action should be executed.</param>
 /// <param name="action">The action to execute on the owning thread of the specified control. The action is invoked across threads.
 /// </param>
 /// <returns>A value indicating whether the action was executed. If the control has been disposed at the time the action is ready
 /// to execute then it will not execute and the return value is false; otherwise, it is true.</returns>
 private static bool CrossThreadInvoke(Control control, Action action)
 {
     // On entering this method, we know implicitly the control has a valid window handle and a cross-thread call is required.
     IAsyncResult asyncResult;
     bool invoked = false;
     try
     {
         // We use BeginInvoke so we can get access to the wait handle being used. The normal Invoke also uses a wait handle whilst
         // it waits for the message to be processed but fails to release it, requiring that the handle be finalized. We'll step in
         // and release it deterministically.
         // The use of the MethodInvoker delegate here is intentional. The internal mechanism that process invoked calls will
         // attempt to cast to this delegate (and several others) and invoke them directly which is faster than having to invoke a
         // dynamic delegate. Despite having the same signature, an Action delegate cannot be cast to the MethodInvoker delegate.
         asyncResult = control.BeginInvoke(new MethodInvoker(() =>
         {
             // It is possible our request was posted, but that a message earlier in the queue destroys the control. Our request
             // will still be processed but the control will no longer be valid so we will not attempt to run the specified actions.
             if (control.IsDisposed)
                 return;
             // The control is still valid and since we are on the UI thread, we can now safely run the actions without fear of
             // disposal.
             invoked = true;
             action();
         }));
     }
     catch (InvalidOperationException)
     {
         // If a window handle no longer exists, the control was disposed before we could make our call to BeginInvoke.
         return false;
     }
     try
     {
         // We need to wait on the completion of our action so our method completes synchronously.
         control.EndInvoke(asyncResult);
     }
     catch (ObjectDisposedException)
     {
         // The control can be disposed before we are able to wait on the result. We can ignore this as we have our flag to see if
         // the action was executed.
     }
     // Release the wait handle so it does not have to be finalized.
     asyncResult.AsyncWaitHandle.Dispose();
     // If we get this far, we know our wrapper method was executed but we need to use this flag in case we bailed from executing
     // the specified actions because the control was disposed by the time our wrapper came to execute.
     return invoked;
 }
Example #7
0
		public void InvokeException1 () {
			Control c = new Control ();
			IAsyncResult result;

			result = c.BeginInvoke (new TestDelegate (delegate_call));
			c.EndInvoke (result);
		}
 /// <summary>
 /// Calls EndInvoke on <paramref name="asyncResult"/> and disposes of the wait handle.
 /// </summary>
 /// <param name="control">The control to invoke upon.</param>
 /// <param name="asyncResult">The async result on which to await a result.</param>
 private static void EndAndDisposeAsyncResult(Control control, IAsyncResult asyncResult)
 {
     try
     {
         control.EndInvoke(asyncResult);
     }
     finally
     {
         asyncResult.AsyncWaitHandle.Dispose();
     }
 }
Example #9
0
 /// <summary>
 /// .net2.0中线程安全访问控件扩展方法,可以获取返回值,可能还有其它问题
 /// </summary>
 /// CrossThreadCalls.SafeInvoke(this.statusStrip1, new CrossThreadCalls.TaskDelegate(delegate()
 /// {
 ///    tssStatus.Text = "开始任务...";
 /// }));
 /// CrossThreadCalls.SafeInvoke(this.rtxtChat, new CrossThreadCalls.TaskDelegate(delegate()
 /// {
 ///     rtxtChat.AppendText("测试中");
 /// }));
 /// 参考:http://wenku.baidu.com/view/f0b3ac4733687e21af45a9f9.html
 /// <summary>
 public static void SafeInvoke(Control control, TaskDelegate handler)
 {
     if (control.InvokeRequired)
     {
         while (!control.IsHandleCreated)
         {
             if (control.Disposing || control.IsDisposed)
                 return;
         }
         IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
         control.EndInvoke(result);//获取委托执行结果的返回值
         return;
     }
     IAsyncResult result2 = control.BeginInvoke(handler);
     control.EndInvoke(result2);
 }