c# 线程问题

          //子线程调用主线程方法一
                                //this.Invoke(new Action(() => {
                                //    dgvScanChip.DataSource = SaveChipList;
                                //}));
                                //子线程调用主线程方法一
                                //ControlInvoker.Invoke(this, delegate
                                //{
                                //    dgvScanChip.DataSource = SaveChipList;
                                //});

 

 

 public static class ControlInvoker
    {
        private static readonly Logger logger = LogManager.GetLogger("DefaultLog");
        public static void Invoke(Control ctl, MethodInvoker method)
        {
            try
            {
                if (!ctl.IsHandleCreated)
                    return;

                if (ctl.IsDisposed)
                    return;

                if (ctl.InvokeRequired)
                {
                    ctl.Invoke(method);
                }
                else
                {
                    method();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "ControlInvoker异常");
            }

        }
    }

this.Invoke(new MethodInvoker(() =>
{
    this.rTxtLog.AppendText("在线程内调用主线程中控件 " + Environment.NewLine);
}));

 

异步委托:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 线程与异步委托练习
{
    class Program
    {
        //声明一个委托,
        public delegate int AddFunDel(int a, int b);
        static void Main(string[] args)
        {
            Console.WriteLine("主线程{0},已启动...", Thread.CurrentThread.ManagedThreadId);
            #region 线程
            ////ParameterizedThreadStart  有参委托
            ////ThreadStart   无参委托
            //Thread thread = new Thread(new ThreadStart(MyFun));
            ////设置线程名称 给程序员看的。
            //thread.Name = "MyFun";
            ////设置为后台线程。当主线程被关闭时,后台子线程自动被关闭。
            //thread.IsBackground = true;
            ////更改状态,并没有执行,只是告诉CPU,可以执行了。
            //thread.Start();
            #endregion

            #region 有参线程
            ////Thread thread2 = new Thread(new ParameterizedThreadStart(MyFun2));
            //Thread thread2 = new Thread(a => {
            //    while (true)
            //    {
            //        Console.WriteLine("子线程{0},正在执行中。参数值:{1}", Thread.CurrentThread.ManagedThreadId, a);
            //        Thread.Sleep(1000);
            //    }
            //});
            //thread2.Name = "MyFun2";
            //thread2.IsBackground = true;
            ////设置优先级,只是建议告诉CPU处理。
            //thread2.Priority = ThreadPriority.Highest;
            //thread2.Start(99);
            #endregion

            #region 异步委托
            //AddFunDel aDel = new AddFunDel(AddFun);
            ////通过异步调用这个委托
            //IAsyncResult iresult = aDel.BeginInvoke(3, 5, null, null);
            ////...异步委托,在新建子线程中执行委托中方法,主线程被阻塞状态。
            //int num = aDel.EndInvoke(iresult);
            //Console.WriteLine("计算结果:{0} , 执行线程{1}", num, Thread.CurrentThread.ManagedThreadId);
            #endregion

            #region 异步委托回调函数
            AddFunDel aDel = new AddFunDel(AddFun);
            //AsyncCallback
            IAsyncResult iresult = aDel.BeginInvoke(3, 5, new AsyncCallback(MyAsyncCallback), 30);
            //主线程不会阻塞
            while (!iresult.IsCompleted) //IsCompleted 检测异步操作是否已完成。
            {
                Console.WriteLine("主线程继续执行中...");
                Thread.Sleep(1000);
            }
            #endregion
            Console.ReadKey();
        }

        static void MyFun()
        {
            while (true)
            {
                Console.WriteLine("子线程{0},正在执行中。", Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(1000);
            }
        }

        static void MyFun2(object a)
        {
            Console.WriteLine("子线程{0},正在执行中。参数值:{1}", Thread.CurrentThread.ManagedThreadId, a);
        }

        static int AddFun(int a, int b)
        {
            Console.WriteLine("子线程{0},正在执行中,开始运算a+b", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(5000);
            return a + b;
        }

        //异步委托回调函数
        static void MyAsyncCallback(IAsyncResult result)
        {
            AsyncResult aResult = (AsyncResult)result; //封装类 通过接口 实现多态 
            AddFunDel addDel = (AddFunDel)aResult.AsyncDelegate; //封装委托
            int num = addDel.EndInvoke(result);  //获取异步操作结果
            Console.WriteLine("计算结果:{0} , 执行线程{1}", num, Thread.CurrentThread.ManagedThreadId);
            int i = (int)aResult.AsyncState; //BeginInvoke方法中最后一个参数
            Console.WriteLine("BeginInvoke最后一个参数调用:{0}", i);
        }
    }
}

 

posted @ 2019-09-02 11:49  芮源  阅读(235)  评论(0编辑  收藏  举报