c# 线程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Invoke
{
    public delegate int DeleAdd(int i, string name);

    class Program
    {

        static void Main(string[] args)
        {
            DeleAdd da=new DeleAdd(GoAdd);
            Invoked id = new Invoked(da);
            #region 启动一个线程 1
            ParameterizedThreadStart pts = new ParameterizedThreadStart(GetInvoked);
            Thread td = new Thread(pts);
            td.Start(id);
            #endregion
           

            #region 启动另一个线程监视线程1是否完成
            ParameterizedThreadStart pts2 = new ParameterizedThreadStart(GetBack);
            Thread td2 = new Thread(pts2);
            td2.Start(id);
            #endregion

            #region 直接使用委托
            ThreadStart tss = delegate { GoAdd(1, ""); };
            new Thread(tss).Start();
            #endregion


            Console.WriteLine(".................主程序end了");

            Console.ReadKey();

        }

        public static void GetBack(object s)
        {
            Invoked id = s as Invoked;
            while (!id.IsBack)
            {
                Console.WriteLine("...........线程一未完成");
            }
            Console.WriteLine("线程一完成");
        }
        public static void GetInvoked(object s)
        {
            Invoked id = s as Invoked;
            id.DoAdd();
        }
        public static int GoAdd(int i, string name)
        {
            Thread.Sleep(i * 100);
            return 10000;
        }

    }
    public class Invoked
    {
        public DeleAdd add { get; set; }
        public bool IsBack { get; set; }
        public Invoked(DeleAdd a)
        {
            add = a;
            IsBack = false;
        }
        public void DoAdd()
        {
            IAsyncResult ir = add.BeginInvoke(10, "上上", null, null);
            while (!ir.IsCompleted)
            {
                IsBack = ir.IsCompleted;
                Console.WriteLine("线程2正在加载。。。");
            }
            IsBack = ir.IsCompleted;
            Console.WriteLine(add.EndInvoke(ir) + "完成");
        }
    }
}

 

private delegate int MyMethod();
private int method()
{
    Thread.Sleep(10000);
    return 100;
}
private void MethodCompleted(IAsyncResult asyncResult)
{
    if (asyncResult == null) return;
    textBox1.Text = (asyncResult.AsyncState as 
    MyMethod).EndInvoke(asyncResult).ToString();
}

private void button1_Click(object sender, EventArgs e)
{

    MyMethod my = method;
    IAsyncResult asyncResult = my.BeginInvoke(MethodCompleted, my);
}

 

posted on 2012-11-09 10:41  R.Ray  阅读(97)  评论(0)    收藏  举报

导航