2 qq405165798 qq405165798 于 2016.04.05 13:21 提问

Begininvoke中嵌套Invoke发生了阻塞,求解决

为什么button2_Click()不能正确执行?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication35
{
    public partial class Form2 : Form
    {

        public Form2()
        {
            InitializeComponent();
            Button btn1 = new Button();
            btn1.Text = "btn1"; btn1.Dock = DockStyle.Left;
            btn1.Click += this.button1_Click;
            this.Controls.Add(btn1);
            Button btn2 = new Button();
            btn2.Text = "btn2";  btn2.Dock = DockStyle.Left;
            btn2.Click += this.button2_Click;
            this.Controls.Add(btn2);           
        }


        /// <summary>
        /// 可以正确执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            ((Button)sender).Text = "Running...";
            dlg_void_void pf = new dlg_void_void(SetFormText);
            var aysncRst = this.BeginInvoke(pf);
            this.EndInvoke(aysncRst);
            ((Button)sender).Text = "Complete";
        }
        /// <summary>
        /// 在执行后阻塞在SetFormText()的 this.Invoke(pf);
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            ((Button)sender).Text = "Running...";
            dlg_void_void pf = new dlg_void_void(SetFormText);
            var aysncRst = pf.BeginInvoke(null, null);
            pf.EndInvoke(aysncRst);
            ((Button)sender).Text = "Complete";

        }
        delegate void dlg_void_void();
        private void SetFormText()
        {
            if (this.InvokeRequired)
            {
                dlg_void_void pf = new dlg_void_void(SetFormText);
                this.Invoke(pf);
                return;
            }

            var sum = 0;
            for (int i = 0; i < 10; i++)
            {
                sum += i;
            }
            this.Text = sum.ToString();
        }
    }
}


1个回答

caozhy
caozhy   Ds   Rxr 2016.04.05 14:07

你写
pf.EndInvoke(aysncRst);
能不阻塞么?

去掉这一行,把((Button)sender).Text = "Complete";写在BeginInvoke的第二个参数的委托中

这里有个例子
http://www.bubuko.com/infodetail-578212.html

qq405165798
qq405165798 请移步http://bbs.csdn.net/topics/391928853
一年多之前 回复
qq405165798
qq405165798 我奇怪的是,, 正常的阻塞应该不超过10ms,这个Invoke中的阻塞永远不会结束,貌似是死了. 这两种调用方法,都是BeginInvoke开始,都会在产生的线程中调用 Invoke,都在主线程中EndInvoke. 为什么第一种只要等10ms就完成,第二种就永久的卡死了呢?
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!