System.Threading.Timer终止PowerShell控制台
在PowerShell控制台中运行此操作时:System.Threading.Timer终止PowerShell控制台,powershell,Powershell,在PowerShell控制台中运行此操作时: $callback = [System.Threading.TimerCallback]{ param($state) } $timer = [System.Threading.Timer]::new($callback, $null, [timespan]::Zero, [timespan]::FromSeconds(1)) 然后,一旦调用了$callback(通过将[timespan]::零延迟更改为更长延迟,我确定这
$callback = [System.Threading.TimerCallback]{
param($state)
}
$timer = [System.Threading.Timer]::new($callback, $null,
[timespan]::Zero,
[timespan]::FromSeconds(1))
然后,一旦调用了$callback
(通过将[timespan]::零延迟更改为更长延迟,我确定这是根本原因),整个控制台进程就会崩溃,表示powershell已停止工作
原因可能是什么?如何克服此问题?错误是:
此线程中没有可用于运行脚本的运行空间。你可以
在的DefaultRunspace属性中提供一个
System.Management.Automation.Runspaces.Runspace类型
源于
System.Management.Automation.ScriptBlock.GetContextFromTLS()
代表是问题所在。我就是这样让它工作的:
$helper = @'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Management.Automation.Runspaces;
public class RunspacedDelegateFactory
{
public static Delegate NewRunspacedDelegate(Delegate _delegate, Runspace runspace)
{
Action setRunspace = () => Runspace.DefaultRunspace = runspace;
return ConcatActionToDelegate(setRunspace, _delegate);
}
private static Expression ExpressionInvoke(Delegate _delegate, params Expression[] arguments)
{
var invokeMethod = _delegate.GetType().GetMethod("Invoke");
return Expression.Call(Expression.Constant(_delegate), invokeMethod, arguments);
}
public static Delegate ConcatActionToDelegate(Action a, Delegate d)
{
var parameters =
d.GetType().GetMethod("Invoke").GetParameters()
.Select(p => Expression.Parameter(p.ParameterType, p.Name))
.ToArray();
Expression body = Expression.Block(ExpressionInvoke(a), ExpressionInvoke(d, parameters));
var lambda = Expression.Lambda(d.GetType(), body, parameters);
var compiled = lambda.Compile();
return compiled;
}
}
'@
add-type -TypeDefinition $helper
$runspacedDelegate = [RunspacedDelegateFactory]::NewRunspacedDelegate($callback, [Runspace]::DefaultRunspace)
$timer = [System.Threading.Timer]::new(
$runspacedDelegate,
$null,
[timespan]::Zero,
[timespan]::FromSeconds(1))
我从你那里借了新的RunspacedDelegate
哇,真是大惊小怪。。。令人印象深刻,但不确定是否值得。。为什么仅仅发送一个代表就这么难呢?顺便问一下,你是如何得到错误的?我的控制台刚刚崩溃。它记录在事件日志中。也就是说,全文错误是从PowerShell 6输出的。