我有一个这样定义的权限列表:
private List<PermissionItem> permissionItems;
private ReadOnlyCollection<PermissionItem> permissionItemsReadOnly;
此列表通过后台线程从 Web 服务中检索。只读版本由列表版本填充。
我将此列表公开给我的(相当大的)应用程序的其余部分,如下所示:
public IQueryable<PermissionItem> PermissionItems
{
get
{
// Make sure that the permissions have returned.
// If they have not then we need to wait for that to happen.
if (!doneLoadingPermissions.WaitOne(10000))
throw new ApplicationException("Could not load permissions");
return permissionItemsReadOnly.AsQueryable();
}
}
这一切都很好。用户可以请求权限并在加载后获得权限。
但是如果我在构造函数中(在不同的类中)有这样的代码:
ThisClassInstanceOfThePermisssions = SecurityStuff.PermissionItems;
然后我相当确定在权限返回之前会阻塞。但在实际使用权限之前,它不需要阻塞。
我读到 IQueryable 是“延迟加载”。 (我在我的 Entity Framework 代码中使用了这个特性。)
有没有办法可以更改它以允许随时引用我的 IQueryable,并且仅在实际使用数据时阻止?
注意:这是一个“不错”的功能。实际上加载权限不会花费太长时间。因此,如果这是一个“自己动手”的查询/表达式内容,那么我可能会通过。但我很好奇要让它发挥作用需要什么。
最佳答案
是的,这是可能的。首先,您可能应该切换到 IEnumerable,因为您没有使用任何 IQueryable 功能。接下来,您需要实现一个新的迭代器:
public IEnumerable<PermissionItem> PermissionItems
{
get
{
return GetPermissionItems();
}
}
static IEnumerable<PermissionItem> GetPermissionItems()
{
// Make sure that the permissions have returned.
// If they have not then we need to wait for that to happen.
if (!doneLoadingPermissions.WaitOne(10000))
throw new ApplicationException("Could not load permissions");
foreach (var item in permissionItemsReadOnly) yield return item;
}
只有当属性的调用者枚举了 IEnumerable
时,事件才会被等待。只是返回它没有任何作用。
关于c# - 如何使用我自己的由列表支持的 IQueryable 进行延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873150/