gpt4 book ai didi

c# - 请向我解释这个 BackgroundWorker 事件

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:38 24 4
gpt4 key购买 nike

我正在试验 BackgroundWorker,并尝试根据事件通知我的主线程。这些东西对我来说都是新的,想问一下,我做的好不好。

我简化了我的一个 winforms 问题,通过以下方式:(它只有 1 个按钮,当我按下它时在另一个线程中计数到 10)

public partial class Form1 : Form
{
public void Subscribe(CountToTen c)
{
c.HandleWorkerEvent += new CountToTen.WorkerHandler(OtherThreadFinished);
}
private void OtherThreadFinished(CountToTen c, EventArgs e)
{
Debug.WriteLine("I'm ready !!!");
}

public Form1()
{
InitializeComponent();
}

private void btn_do_Click(object sender, EventArgs e)
{
CountToTen newThread = new CountToTen();
Subscribe(newThread);
newThread.StartCountingAndReportIfFinished();
}
}

CountToTen 类:

public class CountToTen
{

public event WorkerHandler HandleWorkerEvent;
public EventArgs e;
public delegate void WorkerHandler(CountToTen c, EventArgs e);
public void StartCountingAndReportIfFinished()
{
BackgroundWorker worker = new BackgroundWorker();

worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(300);
Debug.WriteLine("Counting :" + i.ToString());

}
};

worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs args)
{
Debug.WriteLine("Fromt Thread2 : I am finished!");
if (HandleWorkerEvent != null)
{
HandleWorkerEvent(this, e);
}
});

worker.RunWorkerAsync();
worker.Dispose();
}
}

我试图创建一个事件,当 BW 完成时,并在我的主窗体中订阅这个事件。它工作正常,但是,我真的不明白这一行发生了什么:

worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs args)
{
Debug.WriteLine("Fromt Thread2 : I am finished!");
if (HandleWorkerEvent != null)
{
HandleWorkerEvent(this, e);
}
});

我不是在这里为我的 BW 创建一个事件,当它完成时,然后为主线程调用另一个吗?这不是矫枉过正吗?我也可以直接订阅 RunWorkerCompleteEventHandler 吗?

这里有点糊涂,请初学者指教。谢谢

最佳答案

这是对 BackgroundWorker 的 RunWorkerCompleted 事件的订阅。您可以使用匿名方法或命名方法来执行此操作。您也可以通过这种方式删除委托(delegate)类型声明:

worker.RunWorkerCompleted += (o, args) => 
{
// raise HandleWorkerEvent if there is any subscriber exists
if (HandleWorkerEvent != null)
HandleWorkerEvent(this, e);

worker.Dispose();
};

使用命名方法,这看起来像

worker.RunWorkerCompleted += Worker_RunWorkerCompleted;

处理程序:

void Worker_RunWorkerCompleted(object o, RunWorkerCompletedEventArgs args)
{
if (HandleWorkerEvent != null)
HandleWorkerEvent(this, e);

((BackgroundWorker)o).Dispose();
}

顺便说一句,我认为上课比较好,它只有数到十的逻辑。在您的表单上创建 BackgroundWorker,并在 DoWork 事件处理程序中使用此类。此外,表单将处置其所有组件。

关于c# - 请向我解释这个 BackgroundWorker 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14398057/

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