The Perfect Day

分享技术,编写未来

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

引自博客:Yes I Can 什么是.Net异步调用机制

 

代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.ComponentModel;//ISynchronizeInvoke
using System.Runtime.Remoting.Messaging;//AsyncResult
using System.Windows.Forms;
using System.Threading;

namespace WinApp
{
    
public class AsyncQueryHelper
    {
        FrmProgressBar frmProgressBar 
= null;

        
public AsyncQueryHelper()
        {
            frmProgressBar 
= new FrmProgressBar(10);
        }

        
public delegate DataSet ExecQueryHandler(DataSet dsRequest);
        
public ExecQueryHandler execQueryHandlerInstance = null;

        
private AsyncCallback asyncCallbackInstance = null;
        
public void ExecQuery(DataSet dsRequest)
        {
            frmProgressBar.StartThread();
            asyncCallbackInstance 
= new AsyncCallback(ExecAsyncCallBack);//<=>asyncCallbackInstance = ExecAsyncCallBack;

            
if (execQueryHandlerInstance != null)
            {
                
//execQueryHandlerInstance.BeginInvoke(dsRequest, asyncCallbackInstance, execQueryHandlerInstance);
                IAsyncResult result = execQueryHandlerInstance.BeginInvoke(dsRequest, ExecAsyncCallBack, execQueryHandlerInstance);//同上

                
//=======================WaitOne=======================//
                
//阻碍当前线程,直到异步调用结束
                result.AsyncWaitHandle.WaitOne();
                
//开始其他工作.
                
//DoAnotherWork();

                
//=======================WaitAll=======================//
                /*
                IAsyncResult result1 = execQueryHandlerInstance.BeginInvoke(dsRequest, ExecAsyncCallBack, execQueryHandlerInstance);
                IAsyncResult result2 = execQueryHandlerInstance.BeginInvoke(dsRequest, ExecAsyncCallBack, execQueryHandlerInstance);
                //把所有异步的句柄保存到WaitHandle 对象中
                WaitHandle[] waitHandles = { result1.AsyncWaitHandle, result2.AsyncWaitHandle };
                //阻碍当前线程,直到所有异步调用结束
                WaitHandle.WaitAll(waitHandles);
                //开始其他工作
                //DoAnotherWork();
                
*/

                
//====WaitAny:可以使用 WaitAny 来指定某个/某几个委托先等待=====//
                /*
                 WaitHandle[] oneWaitHandle = { result1.AsyncWaitHandle };
                 WaitHandle.WaitAny(oneWaitHandle);
                 //开始其他工作
                 //DoAnotherWork();
                
*/
            }
        }

        
public delegate void BindDataToGrid(DataSet dsReponse);
        
public BindDataToGrid bindDataToGridInstance = null;

        
public DataGridView dataGridView = null;
        
public void ExecAsyncCallBack(IAsyncResult asyncResult)
        {
            endHandlerInstance 
= new EndHandler(frmProgressBar.EndThread);
            frmProgressBar.BeginInvoke(endHandlerInstance, 
null);//执行控件的BeginInvoke

            
////======================1=========================////
            //此处的asyncResult.AsyncState对象就是BeginInvoke里的最后一个参数
            /*
            ExecQueryHandler execQueryHandler = asyncResult.AsyncState as ExecQueryHandler;
            DataSet dsReponse = null;
            if (asyncResult.IsCompleted)
            {
                if (execQueryHandler != null)
                {
                    dsReponse = new DataSet();
                    dsReponse = execQueryHandler.EndInvoke(asyncResult);
                    ISynchronizeInvoke async = this.dataGridView;
                    if (async.InvokeRequired)
                    {
                        async.Invoke(bindDataToGridInstance, new object[] { dsReponse });
                    }
                }
            }
            
*/

            
////======================2=========================////
            AsyncResult originAsyncResult = asyncResult as AsyncResult;
            
if (originAsyncResult != null)
            {
                ExecQueryHandler execQuery 
= (ExecQueryHandler)originAsyncResult.AsyncDelegate;
                DataSet dsReponse 
= execQuery.EndInvoke(asyncResult);

                ISynchronizeInvoke async 
= this.dataGridView;
                
//InvokeRequired == false表示来自主线程;为true表示来自异步线程
                if (dataGridView != null && bindDataToGridInstance != null)
                {
                    
if (async.InvokeRequired)
                    {
                        async.Invoke(bindDataToGridInstance, 
new object[] { dsReponse });
                    }
                }
                asyncResult.AsyncWaitHandle.Close();
//显示的释放资源
            }
        }

        
public delegate void SendRequestHandler();
        
public SendRequestHandler sendRequestHandlerInstance = null;

        
public delegate void EndHandler();
        
public EndHandler endHandlerInstance = null;


        
static void DoAnotherJob()
        {
            Thread.Sleep(
1000);//需要1秒才能完成这个工作
            MessageBox.Show("[{0}]:Do Another Job", DateTime.Now.ToString());
        }

    }
}

 

 

 

代码
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace WinApp
{
    
public class AsyncReadWrite
    {
        
//同步读文件
        public static string SyncRead()
        {
            
string path = @"d:\test.txt";
            FileStream fs 
= new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 20480false);
            StringBuilder sbReadResult 
= new StringBuilder();
            
using (fs)
            {
                
byte[] data = new byte[1024];
                
int nbyteReads;
                
do
                {
                    nbyteReads 
= fs.Read(data, 0, data.Length);
                    sbReadResult.Append(Encoding.Default.GetString(data, 
0, nbyteReads));
                } 
while (nbyteReads > 0);
                
//Console.WriteLine(sbReadResult.ToString());
            }
            
//Console.ReadLine();
            return sbReadResult.ToString().Trim();
        }

        
//异步读文件
        public static string AsyncRead()
        {
            
string path = @"d:\Query.txt";
            
byte[] data = new byte[1024];
            FileStream fs 
= new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 20480true);
            StringBuilder sbReadResult 
= new StringBuilder();
            AsyncCallback asyncCallback 
= null;
            
//匿名方法
            asyncCallback = delegate(IAsyncResult asyncResult)
            {
                
int nRead = fs.EndRead(asyncResult);
                sbReadResult.Append(Encoding.Default.GetString(data, 
0, nRead));

                
if (nRead > 0)
                {
                    fs.BeginRead(data, 
01024, asyncCallback, null);
                }
                
else
                {
                    fs.Close();
//显示释放托管堆资源
                }
            };
            IAsyncResult asyncReadResult 
= fs.BeginRead(data, 01024, asyncCallback, null);
            
return sbReadResult.ToString().Trim();
        }

        
//异步写文件
        public static void AsyncWrite(string content)
        {
            
string path = @"d:\write.txt";
            FileStream fs 
= new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 20480true);
            
byte[] data = Encoding.Default.GetBytes(content);
            AsyncCallback asyncCallback 
= null;
            asyncCallback 
= delegate(IAsyncResult async)
            {
                fs.EndWrite(async);
                fs.Close();
//显示释放托管堆资源
            };
            IAsyncResult asyncWriteResult 
= fs.BeginWrite(data, 0, data.Length, asyncCallback, null);
            Console.ReadLine();
        }
    }
}

 

 

posted on 2009-09-11 12:21  StephenJu  阅读(519)  评论(0编辑  收藏  举报