Mou*_*Mou 0 c# multithreading backgroundworker threadpool
我很多时候在线程的帮助下调用方法
static void Main( string[] args )
{
Thread t = new Thread( MyFunction );
t.Start();
}
static void MyFunction()
{
//code goes here
}
Run Code Online (Sandbox Code Playgroud)
有些时候我ThreadPool也喜欢上课
System.Threading.ThreadPool.QueueUserWorkItem(delegate {
MyFunction();
}, null);
Run Code Online (Sandbox Code Playgroud)
但我不明白在线程类或ThreadPool类的帮助下调用任何方法有什么区别
所以我正在寻找一个关于Thread和ThreadPoolclass 之间有什么区别的好讨论.还需要知道何时应该使用Thread类来调用方法以及何时ThreadPool调用任何方法的类?如果可能的话,还要与样本代码一起讨论样本情况
另一个非常重要的问题是,如果我启动多个线程,那么我的应用程序性能会变低还是差?如果是,那么告诉我为什么......?
现在还告诉我什么是BackgroundWorker类以及它与Thread和ThreadPool类的不同之处.我听到BackgroundWorker该类还创建了一个单独的线程来运行任何方法.所以请讨论它与Thread和ThreadPoolclass的不同之处以及何时应该去BackgroundWorker上课.
这是一个小样本代码 BackgroundWorker
private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
// this allows our worker to report progress during work
bw.WorkerReportsProgress = true;
// what to do in the background thread
bw.DoWork += new DoWorkEventHandler(
delegate(object o, DoWorkEventArgs args)
{
BackgroundWorker b = o as BackgroundWorker;
// do some simple processing for 10 seconds
for (int i = 1; i <= 10; i++)
{
// report the progress in percent
b.ReportProgress(i * 10);
Thread.Sleep(1000);
}
});
// what to do when progress changed (update the progress bar for example)
bw.ProgressChanged += new ProgressChangedEventHandler(
delegate(object o, ProgressChangedEventArgs args)
{
label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
});
// what to do when worker completes its task (notify the user)
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate(object o, RunWorkerCompletedEventArgs args)
{
label1.Text = "Finished!";
});
bw.RunWorkerAsync();
}
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 21
但我不明白在线程类或ThreadPool类的帮助下调用任何方法有什么区别
主要区别在于您是自己管理线程生存期(Thread),还是利用框架已创建的线程"池".
使用ThreadPool.QueueUserWorkItemwill(经常)使用系统中已存在的线程.这意味着你没有开始新线程的开销 - 相反,已经存在一组线程,而你的工作就是在其中一个线程上运行.如果你做了许多短暂的操作,这可能特别有用.
当你使用时new Thread,你实际上会启动一个新的线程,直到你的委托完成它的执行.
请注意,从.NET 4和4.5开始,我建议使用Task和Task<T>类型而不是使用自己的线程ThreadPool.QueueUserWorkItem.这些(默认情况下)使用线程池执行,但提供许多其他有用的抽象,尤其是C#5和await/ asynckeywords.
现在还告诉我什么是BackgroundWorker类以及它与Thread和ThreadPool类的不同之处.H
该BackgroundWorker下课线程池的抽象.它使用ThreadPool队列"工作"(您的DoWork事件处理程序),但也提供额外的功能,允许将进度和完成事件发布回初始SynchronizationContext(在GUI程序中,通常是用户界面线程).这样可以简化您希望在后台线程上运行后台"工作"时更新UI以获取进度或完成通知的任务.
| 归档时间: |
|
| 查看次数: |
7331 次 |
| 最近记录: |