((C#)BackgroundWorker()ProgressChanged不起作用

问题描述 投票:0回答:1

我有一个WPF应用程序,该应用程序由两个线程组成,它们在52周内模拟企业生产和销售商品(每周仅允许一次交易)。我还需要使用后台工作者,以便可以在列表视图中显示数据。截至目前,单击simulate时我的UI冻结,但是我可以看到输出仍在调试终端中运行。我已经尝试了所有我能想到的一切,并且说实话,我得到了老师的帮助,甚至他也找不到有效的解决方案。


  1. 调用Simulate()时冻结UI的原因是什么>>
  2. [当我的代码不同并且我的UI没有冻结时,我的列表视图永远不会更新,因为似乎DataProgress()不起作用-e.UserStart从未迭代。

  3. 模拟按钮调用:

private void Simulate(object sender, RoutedEventArgs e)
{
    // Declare BackgroundWorker
    Data = new ObservableCollection<Operations>();
    worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.WorkerSupportsCancellation = true;
    worker.RunWorkerAsync(52);

    worker.DoWork += ShowData;
    worker.ProgressChanged += DataProgress;
    worker.RunWorkerCompleted += DataToDB;

    Production = new Production(qtyProduction, timeExecProd);
    Sales = new Sales(qtySales, timeExecSales);

    Thread prod = new Thread(Production.Product);
    prod.Start();

    Thread.Sleep(100);

    Thread sales = new Thread(Sales.Sell);
    sales.Start();
}

DoWork:ShowData():

Console.WriteLine("Simulation started | Initial stock : 500");

Production = new Production(qtyProduction, timeExecProd);
Sales = new Sales(qtySales, timeExecSales);

while (Factory.Week < max) // max = 52 
{
    if (worker.CancellationPending) // also this isn't reacting to worker.CancelAsync();
        e.Cancel = true;

   // My teacher tried to call my threads from here, but it breaks the purpose of having 
   // two threads as he was just calling 52 times two functions back to back and therefore
   // wasn't "randomizing" the transactions.

    int progressPercentage = Convert.ToInt32(((double)(Factory.Week) / max) * 100);
    (sender as BackgroundWorker).ReportProgress(progressPercentage, Factory.Week);
}

ProgressChanged:DataProgress():

if (e.UserState != null) // While using debugger, it looks like this is called over & over
{
    Data.Add(new Operations() 
    {
        id = rnd.Next(1,999),
        name = Factory.name,
        qtyStock = Factory.Stock,
        averageStock = Factory.AverageStock,
        week = Factory.Week
    });
    listview.ItemsSource = Data;
}

RunWorkerCompleted:DataToDB():

    // Outputs "Work done" for now.

如果您想知道我调用线程时发生的情况,它看起来像这样:

Sell():

while (Factory.Week <= 52)
{
    lock (obj)
    {
        // some math function callings¸
        Factory.Week++;
    }
    Thread.Sleep(timeExecSales);
}

我应该仅使用第三个线程来更新列表视图吗?我没有看到如何将其与我的静态变量同步。 这是我的第一个学习多线程的项目...

我有点笨拙,甚至连老师也帮不上忙。

我有一个WPF应用程序,它由两个线程组成,它们在52周内模拟企业生产和销售商品(每周仅允许一笔交易)。我需要使用后台工作者作为...

c# wpf multithreading backgroundworker
1个回答
0
投票

一方面,发布的代码中没有足够的上下文来获得完整的图片来回答您的问题准确地

。但是,我们可以仅从您发布的代码中推断出出了什么问题。
© www.soinside.com 2019 - 2024. All rights reserved.