我的 C# Web 应用程序中有一个锁,可防止用户在更新脚本启动后运行它。
我想我会在我的母版页中放置一个通知,让用户知道数据还没有全部存在。
目前我是这样锁定的。
protected void butRefreshData_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ParameterizedThreadStart(UpdateDatabase));
t.Start(this);
//sleep for a bit to ensure that javascript has a chance to get rendered
Thread.Sleep(100);
}
public static void UpdateDatabase(object con)
{
if (Monitor.TryEnter(myLock))
{
Updater.RepopulateDatabase();
Monitor.Exit(myLock);
}
else
{
Common.RegisterStartupScript(con, AlreadyLockedJavaScript);
}
}
我不想做
if(Monitor.TryEnter(myLock))
Monitor.Exit(myLock);
else
//show processing labal
正如我想象的那样,它有可能在实际未运行时显示通知。
我可以使用替代方案吗?
编辑:
大家好,非常感谢您的建议!不幸的是我不能让他们工作......
然而,我结合了 2 个答案的想法并提出了我自己的解决方案。到目前为止它似乎正在工作,但我必须等待该过程完成......
好的,这似乎可行,我将 Repopule 方法分解到它自己的类中。
public static class DataPopulation
{
public static bool IsUpdating = false;
private static string myLock = "My Lock";
private static string LockMessage = @"Sorry, the data repopulation process is already running and cannot be stopped. Please try again later. If the graphs are not slowly filling with data please contact your IT support specialist.";
private static string LockJavaScript = @"alert('" + LockMessage + @"');";
public static void Repopulate(object con)
{
if (Monitor.TryEnter(myLock))
{
IsUpdating = true;
MyProjectRepopulate.MyProjectRepopulate.RepopulateDatabase();
IsUpdating = false;
Monitor.Exit(myLock);
}
else
{
Common.RegisterStartupScript(con, LockJavaScript);
}
}
}
我做主
protected void Page_Load(object sender, EventArgs e)
{
if (DataPopulation.IsUpdating)
lblRefresh.Visible = true;
else
lblRefresh.Visible = false;
}
最佳答案
(假设您知道在处理停止后显示此通知的竞争条件......)
你可以切换到 CountdownEvent .这与 ManualResetEvent
类似,但也提供了 CurrentCount和 IsSet属性,可用于确定是否正在处理某些内容。
关于C#,我可以在不尝试获取锁的情况下检查它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4974729/