【发布时间】:2018-11-09 10:52:46
【问题描述】:
我有一个带有母版页的 asp.net 网页。在服务器端,我有与 mssql 数据库交互的控制台应用程序(定期向数据库插入行)。在后面的网页代码中,我使用 SqlTableDependency 来捕获该操作。问题是:我认为要实现这一点,我需要无限循环中的另一个线程来“监听”并且不阻塞原始 UI 线程。我最常通过某种弹出窗口通知用户,插入已成功完成,但由于它在不同的线程上运行,它根本无法访问页面控件。我尝试了 MessageBox 和 javascript 警报,但没有成功。我做了一些研究,但只在网络表单的情况下得到了答案。有没有办法以某种方式实现这一目标?我也对另一种解决方案感兴趣,但必须在客户端通知用户。这是感兴趣的代码:
public partial class ProdData_Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ThreadStart childref2 = new ThreadStart(NotifySqlChanges);
Thread childThread2 = new Thread(childref2);
childThread2.Start();
} else {
//some code which is not important right now...
}
}
public void NotifySqlChanges()
{
string connString = getConnectionString();
var mapper = new ModelToTableMapper<Prod_Data_Business_Object>();
mapper.AddMapping(c => c.Value, "Value");
using (var dep = new SqlTableDependency<Prod_Data_Business_Object>(connString, "Prod_Data_Business_Object", mapper, null, null, TableDependency.Enums.DmlTriggerType.Insert, false))
{
dep.OnChanged += Changed;
dep.Start();
while (true)
{
//here comes the infinity loop which listens for action
}
}
// Debug.WriteLine("terminated");
}
public void Changed(object sender, RecordChangedEventArgs<ProdData_Bus> e)
{
var changedEntity = e.Entity;
//here would be the perfect place to inform user
//got no idea, how... (Controls derive from System.Web.UI thus cannot
//use Invoke, and ScriptManager.RegisterStartupscript not working
}
}
【问题讨论】:
-
您需要了解the request lifecycle。请求完成后,您无法向用户发送任何新数据,除非用户通过 ajax 调用或类似方式请求数据。
-
感谢您的澄清。我对页面生命周期感到困惑。 :)
标签: c# multithreading user-interface asp.net-webpages