【问题标题】:How to implement PowerShell callbacks correctly with System.RuntimeCaching.MemoryCache如何使用 System.RuntimeCaching.MemoryCache 正确实现 PowerShell 回调
【发布时间】:2017-07-22 15:57:10
【问题描述】:

我正在研究如何使用 PowerShell 构建缓存过期处理程序。以下脚本指示了该目标和预期输出。

$RemovedAction = {
    param([System.Runtime.Caching.CacheEntryRemovedArguments]$Arguments)

    $Key = $Arguments.CacheItem.Key
    $Item = $Arguments.CacheItem
    $RemovedObject = $Arguments.CacheItem.Value
    $RemovedReason = $Arguments.RemovedReason
    Write-Host -ForegroundColor Yellow "About to be removed from cache: $Key : 
    $RemovedReason"
}

# Build a cache, create a policy that references the callback and add items to the cache.
$MC = New-Object System.Runtime.Caching.MemoryCache('Main')

$Policy = New-Object System.Runtime.Caching.CacheItemPolicy 
$Policy.AbsoluteExpiration = (Get-DAte).ToUniversalTime().AddSeconds(4)  #N.B. It's always in UTC.
$Policy.RemovedCallback = $RemovedAction


$A =  [PSCustomObject]@{ Name = 'Albert'; Age = 21 }
$B =  [PSCustomObject]@{ Name = 'Bob'; Age = 21 }


[void]$MC.Set('A',$A, $Policy)
[void]$MC.Set('B',$B, $Policy)

Start-Sleep -Seconds 1
Write-Host -ForegroundColor Green "Expect Bob to be expired immediately..."
[Void]$MC.Remove('B')  # Expect to see  Bob be expired.


Write-Host -ForegroundColor Green "Expect Albert to be expired due to the timeout, clearly it's in the cache at the start of the sleep."
$MC
Start-Sleep -Seconds 6
Write-Host -ForegroundColor Green "See, Albert has gone, as it's not in the cache, but it does not look as thouh the delegate was triggered."
$MC 

这样做的结果是删除“Albert”的显式示例按预期工作,处理程序使用正确的参数调用,但是具有绝对到期时间的隐式示例似乎没有按预期工作。

在后一种情况下,似乎该项目确实从缓存中过期(我们可以从它没有被打印出来的事实中看到)但是似乎确实没有调用回调。

我怀疑这可能是线程问题,但我不清楚这里发生了什么。

这是实现自定义更改监视器回调的垫脚石。

【问题讨论】:

    标签: powershell events caching delegates


    【解决方案1】:

    这个答案晚了一年,但对于任何在这里找到方法的人 - 到期不会触发回调。在数据过期后第一次调用数据是触发回调的原因。见MemoryCache AbsoluteExpiration acting strange

    Start-Sleep -Seconds 6
    $MC.Get('A') | out-null
    Write-Host -ForegroundColor Green "See, Albert has gone, as it's not in the cache, but it does not look as thouh the delegate was triggered."
    

    【讨论】:

    • 您能否详细说明您的答案并发布一些代码用于说明目的?
    • @Artem - 我刚刚编辑了我的答案,以包括我在原始代码中所做的更改,该更改使到期回调触发。
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2020-12-05
    相关资源
    最近更新 更多