C# dll 事件执行 js 回调函数

 

前言:

  由于js 远程请求  XMLHttpRequest() 不支持多线程,所以用C# 写了个dll 多线程远程抓住供js调用。

最初代码为:

  C#代码

/// <summary>
/// 异步请求入口
/// </summary>
/// <param name="url">传入http地址 注意加http</param>
/// <param name="timeoutStr">超时时间</param>
public void AsyncGet(string url, int timeoutStr)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Timeout = timeoutStr;
request.BeginGetResponse(new AsyncCallback(ReadCallBack), request);
}
catch (Exception) { }
} /// <summary>
/// 执行回调时候异步最终拿到值
/// 正常获取反馈值,异常时候值为 timeout
/// </summary>
public string returnContent { get; set; } /// <summary>
/// 执行异步回调请求
/// </summary>
/// <param name="asynchronousResult"></param>
private void ReadCallBack(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest reqeust = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)reqeust.EndGetResponse(asynchronousResult);
StreamReader readContent = new StreamReader(response.GetResponseStream());
returnContent = readContent.ReadToEnd().ToString();
}
catch (Exception)
{
returnContent = "timeout";
}
}

js 代码:
  

var Gtime = 5;
function getUrl (turl) {
if (Gtime==5) {
comActiveX.AsyncGet(turl,Gtime);
}
if (Gtime>0 && comActiveX.returnContent==undefined) {
setTimeout("getUrl('"+turl+"')",1000);
alert(comActiveX.returnContent);
Gtime -- ;
}else{
document.write( comActiveX.returnContent);
}
}

这里存在问题,js必须一直去询问dll 是否获取到数据,直到获取到数据才做下面处理,虽然其中可以做其他事情,但是这跟同步等待没有多大区别。

windows 经典编程 有句话叫“don't call me , I will call you!” ,这就是事件的引入,那么这里可以不可以优化为,当有数据拿到以后自动通知js,js能不能注册一个回调函数。 开始一通尝试,最终找到相关答案:

C# 加入以下代码:

    public delegate void EventHandler(string data);
[Guid("9771B223-6188-4849-B292-C7D9D8173E49")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ControlEvents
{
[DispId(0x60020000)]
void eventsGet(string data);
} /// <summary>
/// 采集类
/// </summary>
[ClassInterface(ClassInterfaceType.AutoDual), ComSourceInterfaces(typeof(ControlEvents))]
public class CollectGood : UserControl
{ public event EventHandler eventsGet; private delegate void UpEventDelegate(string msg); public void Reback(string msg)
{
UpEventDelegate up = new UpEventDelegate(UpEvent);
this.BeginInvoke(up, msg);
}
private void UpEvent(string msg)
{
if (eventsGet != null)
{
eventsGet(msg);
}
} #region httpWebRequest 异步请求Get方法
/// <summary>
/// 异步请求入口
/// </summary>
/// <param name="url">传入http地址 注意加http</param>
/// <param name="timeoutStr">超时时间</param>
public void AsyncGet(string url, int timeoutStr)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Timeout = timeoutStr;
request.BeginGetResponse(new AsyncCallback(ReadCallBack), request);
}
catch (Exception) { }
} /// <summary>
/// 执行回调时候异步最终拿到值
/// 正常获取反馈值,异常时候值为 timeout
/// </summary>
public string returnContent { get; set; } /// <summary>
/// 执行异步回调请求
/// </summary>
/// <param name="asynchronousResult"></param>
private void ReadCallBack(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest reqeust = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)reqeust.EndGetResponse(asynchronousResult);
StreamReader readContent = new StreamReader(response.GetResponseStream());
returnContent = readContent.ReadToEnd().ToString();
Reback(returnContent);
}
catch (Exception)
{
returnContent = "timeout";
}
}
#endregion

js部分:

<OBJECT id="comActiveX" width="" height="" classid="CLSID:7b8bfbe3-7f62-47e0-919c-6aa2315e6db9">
</OBJECT>
<SCRIPT type="text/javascript">
//var comActiveX;
try {
//comActiveX = new ActiveXObject("HttpAsy.CollectGood");
} catch (e) {
// alert("没有注册好");
}
comActiveX.attachEvent("eventsGet",function(msg){alert(msg)}) comActiveX.AsyncGet("http:/www.baidu.com",5);

当运行后就会 弹出 百度源代码

这就实现了异步回调

http://files.cnblogs.com/echosong/http.rar 完整demo下载(先点reg.bat先注册dll)

C# dll 事件执行 js 回调函数的更多相关文章

  1. 脚本加载后执行JS回调函数的方法

    动态脚本简单示例 // IE下: var HEAD = document.getElementsByTagName('head')[0] || document.documentElement var ...

  2. 小兔JS教程(三)-- 彻底攻略JS回调函数

    这一讲来谈谈回调函数. 其实一句话就能概括这个东西: 回调函数就是把一个函数当做参数,传入另一个函数中.传进去的目的仅仅是为了在某个时刻去执行它. 如果不执行,那么你传一个函数进去干嘛呢? 就比如说对 ...

  3. JS回调函数全解析教程

    转自:http://blog.csdn.net/lulei9876/article/details/8494337 自学jQuery的时候,看到一英文词(Callback),顿时背部隐隐冒冷汗.迅速g ...

  4. 如何理解JS回调函数

    1.回调函数英文解释: A callback is a function that is passed as an argument to another function and is execut ...

  5. js回调函数(callback)理解

    Mark! js学习 不喜欢js,但是喜欢jquery,不解释. 自学jquery的时候,看到一英文词(Callback),顿时背部隐隐冒冷汗.迅速google之,发现原来中文翻译成回调.也就是回调函 ...

  6. js回调函数

    自学jQuery的时候,看到一英文词(Callback),顿时背部隐隐冒冷汗.迅速google之,发现原来中文翻译成回调.也就是回调函数了.不懂啊,于是在google回调函数,发现网上的中文解释实在是 ...

  7. JS回调函数的使用和作用

    <html> <head> <title>回调函数(callback)</title> <script language="javasc ...

  8. Node.js 回调函数

    Node.js 回调函数 Node.js 异步编程的直接体现就是回调. 异步编程依托于回调来实现,但不能说使用了回调后程序就异步化了. 回调函数在完成任务后就会被调用,Node 使用了大量的回调函数, ...

  9. JS回调函数--简单易懂有实例

    版权声明:本文为博主原创文章,转载请注明出处 初学js的时候,被回调函数搞得很晕,现在回过头来总结一下什么是回调函数. 我们先来看看回调的英文定义:A callback is a function t ...

随机推荐

  1. hdu 1150 Machine Schedule (经典二分匹配)

    //A组n人 B组m人 //最多有多少人匹配 每人仅仅有匹配一次 # include<stdio.h> # include<string.h> # include<alg ...

  2. asp.net学习之再论sqlDataSource

    原文:asp.net学习之再论sqlDataSource 本节从上一节没有阐述的几个方面,再讨论一下SqlDataSource的用法及注意的事项.     上一节的链接地址如下:http://www. ...

  3. 微软将彻底改变Windows发布方式

    看到网上的新闻信息: 微软上任 CEO 史蒂夫·鲍尔默在职最后一段时间引入了更快的产品公布周期.不再向从前那样,每隔几年公布一次重大产品升级,而是功能一旦开发完成就会推送升级. 显然,现任 CEO 纳 ...

  4. 第5章 原型模式(Protype Pattern)

    原文 第5章 原型模式(Protype Pattern) 定义:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象. 原型图: 原型模式主要用于对象的复制,它的核心是就是类图中的原型类Pro ...

  5. android EditText问题多行文本输入

    一旦习惯了网络和swing在文本框输入,我们Android突然缺乏这样的管制,刚开始使用它是相当费力.为了要实现多行文本输入框和显示.逐一克服这些问题,如下面: 1. 怎么做EditText显示区域在 ...

  6. 【SICP练习】150 练习4.6

    练习4-6 原版的 Exercise 4.6. Let expressions are derived expressions, because (let (( ) - ( )) ) is equiv ...

  7. 阅读小记3(《C编程专家》)

    gets()不检查缓冲区空间.多余的字符将覆盖原来的栈的内容. fgets()的第二个參数说明最大读入的字符数. 假设这个參数值为n,那么fgets()就会读取最多n-1个字符或读完一个换行符为止.两 ...

  8. mysql 的load data infile要使用

    LOAD DATA INFILE从文本文件中读出的声明以极高的速度到表. 1.基本语法 LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'fi ...

  9. 从头开始学JavaScript(一)——基础中的基础

    概要:javascript的组成. 各个组成部分的作用 . 一.javascript的组成   javascript   ECMAScript(核心) DOM(文档对象模型) BOM(浏览器对象模型) ...

  10. java学习笔记1——window7下JDK环境变量配置图解

    1. 首先下载Java安装工具包   http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.ht ...