惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
N
Netflix TechBlog - Medium
腾讯CDC
C
Check Point Blog
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
S
SegmentFault 最新的问题
F
Fortinet All Blogs
美团技术团队
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
F
Full Disclosure
Recorded Future
Recorded Future
D
DataBreaches.Net
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
J
Java Code Geeks
I
InfoQ
Y
Y Combinator Blog
A
About on SuperTechFans
AI
AI
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Forbes - Security
Forbes - Security
W
WeLiveSecurity
M
MIT News - Artificial intelligence
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
Schneier on Security
Schneier on Security
The GitHub Blog
The GitHub Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
Latest news
Latest news
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
V2EX - 技术
V2EX - 技术
Project Zero
Project Zero

博客园 - StephenJu

EntLib--Unity Application Block 1.x DevExpress杂项 简单的异步调用 按s1_Name+uuid为一组拆分DS 枚举 分割dataset:待改进... 序列化 DataGridViewComboBoxColumn的使用 datagridview数据验证 通过关键字查找到dgv相关记录后定位 禁止一个程序启动多个实例 将文本文件的内容写进某个表中 获取Assembly的运行路径 获取ArrayList中的数据(foreach) 关于DataTable里大批量查找的更快速的方法 抽象类 IO DynamicCreateMenu DataTable的简单方法
.Net异步机制
StephenJu · 2009-09-11 · via 博客园 - StephenJu

引自博客: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();
        }
    }
}