【发布时间】:2014-04-04 02:42:49
【问题描述】:
我正在编写一个单线程脚本来对数据库进行大量编程更改。 某些操作会导致数据库执行一些需要一段时间才能完全解决的内部操作。
目前,我的代码包含一个如下所示的方法:
public static void AwaitTemplatePropagation(this Connection conn, DBObject template)
{
while ((int)template["TransactionCount"] > 0)
{
System.Threading.Thread.Sleep(100);
}
}
基本上,它每 100 毫秒轮询一次,直到未完成的事务计数达到 0。
但是,也可以在 DBObject 类上订阅名为 PropertyUpdated 的事件,该事件将在 TransactionCount 属性更改时引发。我更愿意使用它并让服务器让我知道何时继续,而不是轮询。我想它应该看起来像这样:
public static void AwaitTemplatePropagation(this Connection conn, DBObject template)
{
template.PropertyUpdated += ???; // Something?
template.RegisterForPropertyUpdates(new string[] { "TransactionCount" });
// Magic happens?
template.UnregisterPropertyUpdates(new string[] { "TransactionCount" });
template.PropertyUpdated -= ???; // Unsubscribe the event handler
// Return to the calling function in the main thread
}
我无法弄清楚的是,如何编写一个简单地设置订阅的函数,然后 阻塞 直到触发 PropertyChangedEvent 并显示“TransactionCount 现在为零”?那时我想删除订阅并将执行返回到我在主脚本中间的位置。
我使用的是 .NET 4.0,所以 async/await 关键字不可用。我不确定他们是否会提供帮助。
【问题讨论】:
-
顺便说一句,如果你安装了
Microsoft.Bcl.AsyncNuGet 包,你可以在 .NET 4.0 上使用async/await。
标签: c# multithreading events .net-4.0