[英]Update a html element from a thread
What is the easiest way to update an HTML element from another thread? 从另一个线程更新HTML元素的最简单方法是什么?
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. 我有一个带有startJob按钮的Razor / HTML页面,该页面将触发ActionResult在后台线程上启动一个长进程,从此我要后台进程来更新当前状态的Html元素。 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. 仅使用C#确实不可能做到这一点,但是有两种方法可以实现此目标。
Unfortunately dynamically updating a web page isn't really possible without using at least some javascript 不幸的是,如果不使用至少一些JavaScript,实际上不可能动态更新网页
Use async/await
and tasks
instead of another thread: 使用async/await
和tasks
而不是另一个线程:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.