为什么这段代码会冻结我的WPF UI?

时间:2014-05-16 15:47:53

标签: wpf powershell

我正在使用WPF编写一个Powershell脚本,其中显示的方法如下:http://learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/

我遇到跟随代码的问题,将用户界面冻结为" btnTest"单击按钮。我猜这是某种死锁,因为一个线程试图访问另一个线程的资源。我希望有一些解决方法:

Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase
$global:syncHash = [Hashtable]::Synchronized(@{})
$syncHash.Host = $Host
$runSpace = [RunspaceFactory]::CreateRunspace()
$runSpace.ApartmentState,$runSpace.ThreadOptions = “STA”,”ReUseThread”
$runSpace.Open()
$runSpace.SessionStateProxy.SetVariable(“syncHash”,$syncHash)
$cmd = [PowerShell]::Create().AddScript({
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase,System.Windows.Controls
$syncHash.Window = [Windows.Markup.XamlReader]::Parse(@”
       XAML goes here
“@)

$syncHash.btnTest = $global:syncHash.Window.FindName(“btnTest”)
$syncHash.txtText = $global:syncHash.Window.FindName(“txtTest”)

$syncHash.btnTest.Add_Click({
$syncHash.btnTest.IsEnabled = $false
$syncHash.Host.Runspace.Events.GenerateEvent(“btnTestClicked”, $syncHash.btnTest, $null, $null)
})

$syncHash.Window.ShowDialog()
})
$cmd.Runspace = $runSpace
$handle = $cmd.BeginInvoke()

# THIS CODE FREEZES THE UI
Register-EngineEvent -SourceIdentifier “btnTestClicked” -Action {
$global:syncHash.btnTest.Dispatcher.invoke([System.Windows.Threading.DispatcherPriority]::Normal, [action]{$global:syncHash.btnTest.IsEnabled = $true}, $null, $null)
}

任何想法都将不胜感激!

0 个答案:

没有答案