gpt4 book ai didi

c# - backgroundworker+wpf -> 卡住窗口

转载 作者:行者123 更新时间:2023-11-30 17:22:32 26 4
gpt4 key购买 nike

-进度条总是0%

-窗口卡住(而 DoWork r.)

-如果 System.threading.thread.sleep(1) 打开 - 完美运行

有什么问题吗?

private void btnNext_Click(object sender, RoutedEventArgs e)
{
this._worker = new BackgroundWorker();
this._worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
long current = 1;
long max = generalMaxSzam();


for (int i = 1; i <= 30; i++)
{
for (int j = i+1; j <= 30; j++)
{
for (int c = j+1; c <= 30; c++)
{
for (int h = c+1; h <= 30; h++)
{
for (int d = h+1; d <= 30; d++)
{
int percent = Convert.ToInt32(((decimal)current / (decimal)max) * 100);
this._worker.ReportProgress(percent);
current++;
//System.Threading.Thread.Sleep(1); - it works well
}
}
}
}
}
};

this._worker.WorkerReportsProgress = true;

this._worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
this.Close();
};

this._worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
this.statusPG.Value = args.ProgressPercentage;
};

this._worker.RunWorkerAsync();
}

<Window x:Class="SzerencsejatekProgram.Create"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Létrehozás" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="500" Width="700">
<DockPanel>
<Button DockPanel.Dock="Right" Name="btnNext" Width="80" Click="btnNext_Click">Tovább</Button>
<StatusBar DockPanel.Dock="Bottom">
<StatusBar.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</StatusBar.ItemsPanel>
<StatusBarItem Grid.Column="1">
<TextBlock Name="statusText"></TextBlock>
</StatusBarItem>
<StatusBarItem Grid.Column="2">
<ProgressBar Name="statusPG" Width="80" Height="18" IsEnabled="False" />
</StatusBarItem>
<StatusBarItem Grid.Column="3">
<Button Name="statusB" IsCancel="True" IsEnabled="False">Cancel</Button>
</StatusBarItem>
</StatusBar>
</DockPanel>
</Window>

最佳答案

您的代码运行一个非常紧密的循环,并在其中心调用 ReportProgress()。

这意味着您的 MessageQueue 被执行进度更新的请求淹没了。

如果您在 Bgw 线程中构建一些延迟 (Thread.Sleep(100)),您将看到响应能力有所提高。

一个更实用的解决方案是将报告移出到外部循环。在你的情况下:

for (int i = 1; i <= 30; i++)
{
int percent = (i * 100) / 30;
_worker.ReportProgress(percent);
for(int j = 0; ....)
....
}

如果你只有 1 个循环,建立一个延迟:'if ((counter % 100) == 0) ...`

此处您的目标是用户,目标是对 Reportprogress 进行 10 到 100 次调用。

关于c# - backgroundworker+wpf -> 卡住窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681661/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com