CSDN博客

img mableboy

多线程的异步调用(一)

发表于2004/10/6 19:58:00  878人阅读

分类: .NET


最近手头做的项目中,用到了多线程的异步调用。在控制线程中实时的检测硬件的变化,如果硬件发生了某些变化,那么需要通知别的模块做一些相应的操作,为了让这些操作不会影响控制线程的继续运行,就在多线程中使用了异步调用的方法。

using System;

using System.Threading;

 

namespace WindowsApplication1

{

 

    public class Async

    {

        AsyncMenthod dlgt = new AsyncMenthod(DealClass.dealFunction);

 

        private int index = 0;

 

        public Async()

        {

            Thread controlThread = new Thread(new ThreadStart(ControlThreadProc));

            controlThread.Priority=System.Threading.ThreadPriority.AboveNormal;

            controlThread.IsBackground = true;

            controlThread.Start(); //启动一个线程     

        }

 

        public void ControlThreadProc()

        {

            while( index < 5 )

            {  

                index++ ;          

                dlgt.BeginInvoke(index,null,null);//进行异步调用,并且不要求回调等     

                Console.WriteLine( index.ToString() + " Called At "+System.DateTime.Now.ToString() );

                System.Threading.Thread.Sleep(100);

            }

        }

 

        public delegate void AsyncMenthod( int callID ); //和被异步调用的函数必须具有相同的参数,函数名可以不同

 

    }

    public class DealClass

    {

        public static void dealFunction( int callID ) //被异步调用的函数

        {

            Console.WriteLine( callID.ToString() + " Start Deal At "+System.DateTime.Now.ToString());

            System.Threading.Thread.Sleep(2000);

            Console.WriteLine( callID.ToString() +  "Deal Complete At "+System.DateTime.Now.ToString());

           

        }

    }

}

 

输出:

1 Called At 2004-10-6 19:44:01

1 Start Deal At 2004-10-6 19:44:01

2 Called At 2004-10-6 19:44:02

3 Called At 2004-10-6 19:44:02

4 Called At 2004-10-6 19:44:02

5 Called At 2004-10-6 19:44:02

2 Start Deal At 2004-10-6 19:44:02

3 Start Deal At 2004-10-6 19:44:03

4 Start Deal At 2004-10-6 19:44:03

1Deal Complete At 2004-10-6 19:44:03

5 Start Deal At 2004-10-6 19:44:03

2Deal Complete At 2004-10-6 19:44:04

3Deal Complete At 2004-10-6 19:44:05

4Deal Complete At 2004-10-6 19:44:05

5Deal Complete At 2004-10-6 19:44:05


从输出里,很明显的可以看出,控制线程中的函数,并没有等待处理函数处理完毕,而是直接返回,并继续往下执行了。

在处理函数中,它会把这些请求都处理,并且是这样进行处理的:

每来一个请求,它就开始进行处理(类似起一个独立的线程),它不并不会等待前面的处理完毕,然后再来处理新的请求。处理完毕后,返回。

 

阅读全文
0 0

相关文章推荐

img
取 消
img