简体   繁体   中英

Update a html element from a thread

What is the easiest way to update an HTML element from another thread?

I have a Razor/HTML page with a startJob button which will trigger an ActionResult to start a long process on background thread, from that I want to the background tread to update an Html element of the current status. How can I do that?

    public ActionResult StartJob(int[] instList)
    {

            permissionCheck = new Thread(CheckPermissions);
            permissionCheck.Start();


        var jr = new JsonNetResult();
        jr.Formatting = Newtonsoft.Json.Formatting.Indented;
        jr.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        jr.Data = (inQueue <= 0?0:inQueue);

        return jr;
    }


    public void CheckPermissions()
    {
        for (int i = 0; i <= 100; i++)
        {                
            Thread.Sleep(100);
            //update the html element id status message

        }
    }

This isn't really possible out of the box with just C# but there are two ways you could go about implementing this.

  1. Use javascript on the page to poll your server for updates, perhaps through a WebAPI controller.
  2. Use SignalR to update your page dynamically (also requires javascript running on your page)

Unfortunately dynamically updating a web page isn't really possible without using at least some javascript

Use async/await and tasks instead of another thread:

public async ActionResult StartJob(int[] instList)
{
    await CheckPermissions;

    var jr = new JsonNetResult();
    jr.Formatting = Newtonsoft.Json.Formatting.Indented;
    jr.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    jr.Data = (inQueue <= 0?0:inQueue);

    return jr;
}


public async Task CheckPermissions()
{
    for (int i = 0; i <= 100; i++)
    {                
        //Thread.Sleep(100); // Don't use this
        //update the html element id status message

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM