gpt4 book ai didi

C# 多线程设计实例

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

我对 C#/.Net 比较陌生。我正在开发一个需要多线程的桌面应用程序。我想出了下面的模式作为基础。我想知道是否有人可以指出如何在编码、线程安全和高效方面让它变得更好。

希望这是有道理的。


public abstract class ThreadManagerBase
{
// static class variables

private static ThreadManagerBase instance = null;
private static BackgroundWorker thread = null;
private static ProgressBarUIForm progress = null;

/// <summary>
/// Create a new instance of this class. The internals are left to the derived class to figure out.
/// Only one instance of this can run at any time. There should only be the main thread and this thread.
/// </summary>
public abstract static ThreadManagerBase NewInstance();

/// <summary>
/// Clears the instance.
/// </summary>
public static void ClearInstance()
{
instance = null;
}

/// <summary>
/// Initializes the background worker with some presets.
/// Displays progress bar.
/// </summary>
private abstract static void InitializeThread()
{
thread = new BackgroundWorker();

thread.WorkerReportsProgress = true;
thread.WorkerSupportsCancellation = true;

thread.DoWork += new DoWorkEventHandler(thread_DoWork);
thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
thread.ProgressChanged += new ProgressChangedEventHandler(thread_ProgressChanged);

thread.RunWorkerAsync();

progress = new ProgressBarUIForm();

progress.EnableCancelButton = true;

progress.UserCanceled += new EventHandlerCancelClicked(progress_UserCanceled);

progress.ShowDialog();

thread.Dispose();

thread = null;
}

private static void progress_UserCanceled(bool userCanceled)
{
thread.CancelAsync();
}

private static void thread_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress.SetProgressLevel = e.ProgressPercentage;
progress.SetProgressMessage = e.UserState.ToString();
}

private static void thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progress.Close();

progress = null;
}

private static void thread_DoWork(object sender, DoWorkEventArgs e)
{
ProcessWork();
}

private abstract static void ProcessWork()
{
// do actuall stuff here.
// the derived classes will take care of the plumbing.
}
}

最佳答案

你看过Microsoft Parallel Extensions to .NET Framework 3.5吗? ?这是一个相当不错的库,可以完成线程处理中的大量工作。

MSDN 上也有很多关于线程模式的文章,您也应该研究一下。线程可以变得非常复杂非常快。很高兴让其他人了解所有可能出错的重要内容,并将其简化为库或模式。当然,如果您不了解任何特定解决方案的陷阱,那也存在危险。因此,无论选择哪种解决方案,请务必仔细研究。

关于C# 多线程设计实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/596991/

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