线程中的BeginInvoke和EndInvoke [英] BeginInvoke and EndInvoke in thread

查看:68
本文介绍了线程中的BeginInvoke和EndInvoke的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在注释区域EndInvoke中返回null却返回"Step is:number"

Why in the commented area EndInvoke return null while that returns "Step is:number"

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

namespace WindowsFormsApplication28
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            ParameterizedThreadStart start = new ParameterizedThreadStart(startthread);
            System.Threading.Thread u;
            int i = 0;
            while (i < 100)
            {
                u = new System.Threading.Thread(start);
                u.Start(i);

                Thread.Sleep(1000);


                lock (this)
                {
                    try
                    {
                        EndInvoke(g);   // return null??????why?
                    }
                    catch { }
                }

                i++;
            }
        }

        delegate void j(object h);
        j b;

        object h = new object();
        object y = new object();

        void startthread(object m)
        {
            lock (this)
            {
                b = new j(p1);

                if (label1.InvokeRequired)
                {
                    IAsyncResult g = label1.BeginInvoke(b, m);
                }
                else
                {
                    label1.Text = string.Format("Step is :{0}", h.ToString());
                }
            }
        }

        void p1(object h)
        {

            label1.Text = string.Format("Step is :{0}", h.ToString());

        }

        IAsyncResult g;
    }
}

推荐答案

delegate 具有void 返回类型,那么您究竟希望它返回什么?

如果希望它返回设置标签的字符串,则将您的委托更改为:

The delegate has a void return type, so what exactly did you expect it to return?

If you want it to return the string you set the label to, change your delegate to:

delegate string j(object h);



然后执行以下操作:



And then do this:

string p1(object h)
{
    return(label1.Text = string.Format("Step is :{0}", h.ToString()));
}



哦,请选择更好的变量名.不再是1987年了:-)



Oh, and please choose better variable names. It''s not 1987 any more :-)


这篇关于线程中的BeginInvoke和EndInvoke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆