gpt4 book ai didi

c# - 继承问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:16 25 4
gpt4 key购买 nike

我创建了一个类:

public class AbortableBackgroundWorker : BackgroundWorker
{



private Thread workerThread;

protected override void OnDoWork(DoWorkEventArgs e)
{
workerThread = Thread.CurrentThread;
try
{
base.OnDoWork(e);
}
catch (ThreadAbortException)
{
e.Cancel = true; //We must set Cancel property to true!
Thread.ResetAbort(); //Prevents ThreadAbortException propagation
}
}


public void Abort()
{
if (workerThread != null)
{
workerThread.Abort();
workerThread = null;
}
}
}

下面是我的使用方法:

  backgroundWorker1 = new AbortableBackgroundWorker();
//...
backgroundWorker1.RunWorkerAsync();

if (backgroundWorker1.IsBusy == true)
{
backgroundWorker1.Abort();//This method is unavailable :(
backgroundWorker1.Dispose();
}

另一个小问题..这段代码会取消后台 worker 吗?

最佳答案

这不是中止 BackgroundWorker 任务的正确方法...使用 CancelAsync方法和 CancellationPending属性(property)代替。您几乎不应该中止线程,至少在您可以干净地退出此线程时不要中止。

关于c# - 继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6778046/

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