How to execute a JavaScript callback function in a C # DLL event

Source: Internet
Author: User

Objective:

Because JS remote request XMLHttpRequest () does not support multithreading, so in C # write a DLL multithreaded remote capture for JS call.

The initial code is:

C # code

<summary>///Asynchronous Request entry///</summary>///<param name= "url" > incoming HTTP address note plus http& lt;/param>///<param name= "timeoutstr" > Timeout </param> public void asyncget (string url, int TIMEOUTSTR) {try {HttpWebRequest request = (HttpWebRequest) webrequest.cr
                Eate (new Uri (URL)); Request.
                Timeout = Timeoutstr; Request.
            BeginGetResponse (New AsyncCallback (Readcallback), request); The catch (Exception) {}}///<summary>///Execute the callback asynchronously eventually get the value///normal access to the counter
    
        The feed value is timeout///</summary> public string returncontent {get; set;} <summary>///Execute asynchronous callback request///</summary>///<param name= "Asynchronousresult" >& lt;/param>///View This column more highlights: http://www.bianceng.cn/Programming/csharp/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 Code:

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);
        }
    

There is a problem here, JS must always ask the DLL whether to get the data, until the data to do the following processing, although it can do other things, but this is not much different from synchronous waiting.

Windows Classic Programming has the phrase "Don" call me, I will called you!, this is the introduction of the event, so here can not be optimized for, when there is data to automatically notify JS,JS can register a callback function. Start a try and finally find the answer:

C # Adds the following code:

public delegate void EventHandler (string data);
    [Guid ("9771b223-6188-4849-b292-c7d9d8173e49")] [InterfaceType (Cominterfacetype.interfaceisidispatch)] public interface ControlEvents {[DispId (0x60020000
    )] void Events_puhuo (string data); ///<summary>///Collection Class///</summary> [ClassInterface (classinterfacetype.autodual), Com Sourceinterfaces (typeof (ControlEvents))] public class Collectgood:usercontrol {public event Eventh
    
        Andler 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) {even
            Tsget (msg);
     }} #region HttpWebRequest asynchronous request get method///<summary>   Asynchronous request Entry///</summary>///<param name= "url" > Incoming HTTP address note Add http</param>///view this column more Highlights: http://www.bianceng.cn/Programming/csharp////<param name= "timeoutstr" > Timeout </param> Publ IC void asyncget (string url, int timeoutstr) {try {HttpWebRequest Reque
                St = (HttpWebRequest) webrequest.create (new Uri (URL)); Request.
                Timeout = Timeoutstr; Request.
            BeginGetResponse (New AsyncCallback (Readcallback), request); The catch (Exception) {}}///<summary>///Execute the callback asynchronously eventually get the value///normal access to the counter
    
        The feed value is timeout///</summary> public string returncontent {get; set;} <summary>///Execute asynchronous callback request///</summary>///<param name= "Asynchronousresult" >&
 lt;/param> private void Readcallback (IAsyncResult asynchronousresult)       {try {HttpWebRequest reqeust = (HttpWebRequest) asynchronousresult.asyncst
                Ate HttpWebResponse response = (HttpWebResponse) reqeust.
                EndGetResponse (Asynchronousresult); StreamReader readcontent = new StreamReader (response.
                GetResponseStream ()); Returncontent = Readcontent.readtoend ().
                ToString ();
            Reback (returncontent);
            catch (Exception) {returncontent = "timeout"; }} #endregion

JS section:

<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 ("not registered well");
    }
    comactivex.attachevent ("Eventsget", Function (msg) {alert (msg)})
        
    Comactivex.asyncget ("http:/ Www.baidu.com ", 5);

When run will pop up Baidu source code

This implements an asynchronous callback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.