gpt4 book ai didi

c# - 从不同的线程更新 MainWindow 中的进度条

转载 作者:行者123 更新时间:2023-11-30 22:33:07 25 4
gpt4 key购买 nike

我知道这个问题已经被问过好几次了,我花了一整天的时间试图理解其他答案,但由于我是 C# 和 WPF 的新手,所以到目前为止没有任何帮助。我会尽可能多地解释我的确切问题,这样它会直接帮助我。

在我的 MainWindow.xaml 中,我有一个进度条和一些按钮开始一个新线程和一个长计算:

<ProgressBar Height="....... Name="progressBar1"/>
<Button Content="Button" Name="button1" Click="button1_Click" />

现在在我的 MainWindow.xaml.cs 中:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ParameterizedThreadStart(MyLongCalculation));

ParameterClass myParameters = new ParameterClass();
thread.Start(myParameters);
}

public void MyLongCalculations(object myvalues)
{
ParameterClass values = (ParameterClass)myvalues;
//some calculations
}
}

public class ParameterClass
{
//public variables...
}

现在我必须以某种方式在我的方法 MyLongCalculations 中包含一些东西,它将不断更新 progressBar1。但是,我就是无法让它工作。我知道这一切都非常简单,但不幸的是,这是我目前使用 C# 的水平,所以我希望答案不要太复杂并尽可能详细。

最佳答案

后台 worker 非常适合这个。

试试这个:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
// Initialize UI
InitializeComponent();

// Process data
ProcessDataAsync(new ParameterClass { Value = 20 });
}

/// <summary>
/// Processes data asynchronously
/// </summary>
/// <param name="myClass"></param>
private void ProcessDataAsync(ParameterClass myClass)
{
// Background worker
var myWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
};

// Do Work
myWorker.DoWork += delegate(object sender, DoWorkEventArgs e)
{
// Set result
e.Result = MyLongCalculations(myClass);

// Update progress (50 is just an example percent value out of 100)
myWorker.ReportProgress(50);
};

// Progress Changed
myWorker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
{
myProgressBar.Value = e.ProgressPercentage;
};

// Work has been completed
myWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
{
// Work completed, you are back in the UI thread.
TextBox1.Text = (int) e.Result;
};

// Run Worker
myWorker.RunWorkerAsync();
}

/// <summary>
/// Performs calculations
/// </summary>
/// <param name="myvalues"></param>
/// <returns></returns>
public int MyLongCalculations(ParameterClass myvalues)
{
//some calculations
return (myvalues.Value*2);
}

}

/// <summary>
/// Custom class
/// </summary>
public class ParameterClass
{
public int Value { get; set; }
}

关于c# - 从不同的线程更新 MainWindow 中的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8465662/

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