Task , Thread 学习
1.任务StartNew后就开始执行,使用Wait()来确保任务结束后继续
static void Main(string[] args)
{
try
{
int numberOfUsers = 100;
var users = new string[20];
for (int i = 0; i < 20; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
} Task t = Task.Factory.StartNew(() => WriteLog(users[5]));
Thread.Sleep(5000);
Console.WriteLine("Is first one start?");
Task t1 = Task.Factory.StartNew(() => WriteLog(users[6]));
Thread.Sleep(5000);
Console.WriteLine("Are they start?");
Thread.Sleep(5000);
t1.Wait();
Console.WriteLine("Will End soon!");
t.Wait();
Thread.Sleep(500000000); }
catch (Exception ex)
{
Console.WriteLine(string.Format("Time {0}:{1}",DateTime.Now, ex.Message));
Thread.Sleep(500000000);
}
} private static void WriteLog(string userName)
{
Console.WriteLine(string.Format("Begin Time {0}:ProcessId {2} ThreadId {3} {1}", DateTime.Now, userName, System.Diagnostics.Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(5000);
if (userName == "LoadTest2")
{
Thread.Sleep(5000);
throw new Exception("Lazy!");
}
Console.WriteLine(string.Format("End Time {0}:ProcessId {2} ThreadId {3} {1}", DateTime.Now, userName, System.Diagnostics.Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
}
执行效果:
使用ThreadPool也是同样效果:
foreach (string user in users)
{
ThreadPool.QueueUserWorkItem(arg =>
{
WriteLog(user);
});
}
2.10个任务一起执行,须注意WriteLog的参数不能直接使用i,因为在实际开始工作的时候i值已经变成了10
Task[] ts = new Task[10];
for(int i=0;i < numberOfUsers ; i++ )
{
ts[i] = Task.Factory.StartNew((object obj) => {
int j = (int)obj;
WriteLog(users[j]); }, i);
}
Task.WaitAll(ts);
Console.WriteLine("Will End soon!");
Thread.Sleep(500000000);
3.总共20个人,后10个人接着前面10个人后干活,使用ContinueWith , 其中传的prevTask可以得到前面任务的状态
static void Main(string[] args)
{
try
{
int numberOfUsers = 10;
var users = new string[20];
for (int i = 0; i < 20; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
} Task[] ts = new Task[numberOfUsers];
for (int i = 0; i < numberOfUsers; i++)
{
ts[i] = Task.Factory.StartNew((object obj) =>
{
int j = (int)obj;
WriteLog(users[j]);
}, i).ContinueWith((prevTask) =>
{
string exp = string.Empty;
if (prevTask.Exception!=null ) exp = "Exception:" + prevTask.Exception.Message;
Console.WriteLine(string.Format("ID:{0} Status:{1} IsCanceled:{2} IsCompleted:{3} {4}", prevTask.Id, prevTask.Status, prevTask.IsCanceled, prevTask.IsCompleted, exp));
WriteLog(users[9 + prevTask.Id]);
}); } Task.WaitAll(ts);
Console.WriteLine("Will End soon!");
Thread.Sleep(500000000); }
catch (Exception ex)
{
Console.WriteLine(string.Format("Time {0}:{1}",DateTime.Now, ex.Message));
Thread.Sleep(500000000);
}
}
4.获取UI上的值来控制是否cancel一个任务下面的所有子任务,使用CancellationTokenSource
static void Main(string[] args)
{
try
{
int numberOfUsers = 10;
var users = new string[numberOfUsers];
for (int i = 0; i < numberOfUsers; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
}
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
ConcurrentBag<Task> ts = new ConcurrentBag<Task>();
Console.WriteLine("Press any key to begin tasks...");
Console.WriteLine("To terminate the example, press 'c' to cancel and exit...");
Console.ReadKey();
Console.WriteLine(); //Task t = Task.Factory.StartNew(() => WriteLog(users[0], token), token);
//Console.WriteLine("Task {0} executing", t.Id);
//ts.Add(t); Task t = Task.Factory.StartNew(() =>
{
Task tc;
for (int i = 0; i < numberOfUsers; i++)
{
tc = Task.Factory.StartNew((object obj) =>
{
int j = (int)obj;
WriteLog(users[j], token);
}, i, token);
ts.Add(tc);
}
},token);
ts.Add(t); if (Console.ReadKey().KeyChar == 'c')
{
tokenSource.Cancel();
Console.WriteLine("\nTask cancellation requested.");
}
try
{
Task.WaitAll(ts.ToArray());
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
{
if (v is TaskCanceledException)
Console.WriteLine(" TaskCanceledException: Task {0}",
((TaskCanceledException)v).Task.Id);
else
Console.WriteLine(" Exception: {0}", v.GetType().Name);
} }
Console.WriteLine("Will End soon!");
Thread.Sleep(500000000); }
catch (Exception ex)
{
Console.WriteLine(string.Format("Time {0}:{1}",DateTime.Now, ex.Message));
Thread.Sleep(500000000);
}
} private static void WriteLog(string userName, CancellationToken ct)
{
Console.WriteLine(string.Format("Begin Time {0}:ProcessId {2} ThreadId {3} {1}", DateTime.Now, userName, System.Diagnostics.Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
if (userName != "LoadTest1" && userName != "LoadTest2" && userName != "LoadTest3")
{
Thread.Sleep(5000);
}
if (ct.IsCancellationRequested)
{
Console.WriteLine(string.Format("Cancel :{0} ThreadId {1}", userName, Thread.CurrentThread.ManagedThreadId));
ct.ThrowIfCancellationRequested();
}
Console.WriteLine(string.Format("End Time {0}:ProcessId {2} ThreadId {3} {1}", DateTime.Now, userName, System.Diagnostics.Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
}
5.总共10个任务,每次最多3个任务,每当这3个任务中任何一个完成,就会从后续任务中拿出任务来做
static void Main(string[] args)
{
try
{
int numberOfUsers = 10;
var users = new string[numberOfUsers];
for (int i = 0; i < numberOfUsers; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
} Action[] aArr = new Action[numberOfUsers];
int j = 0 ;
for (int i = 0; i < numberOfUsers; i++){
aArr[i] = new Action(() => WriteLog(users[j++]));
} System.Threading.Tasks.ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = 3; try
{
System.Threading.Tasks.Parallel.Invoke(po, aArr);
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
{
if (v is TaskCanceledException)
Console.WriteLine(" TaskCanceledException: Task {0}",
((TaskCanceledException)v).Task.Id);
else
Console.WriteLine(" Exception: {0}", v.Message);
} }
Console.WriteLine("Will End soon!");
Thread.Sleep(500000000); }
catch (Exception ex)
{
Console.WriteLine(string.Format("Time {0}:{1}",DateTime.Now, ex.Message));
Thread.Sleep(500000000);
}
}
6.总共10个任务,每次最多3个任务,而且每次必须3个一起开始
static void Main(string[] args)
{
try
{
int numberOfUsers = 10;
int maxConcurrent = 3;
var users = new string[numberOfUsers];
for (int i = 0; i < numberOfUsers; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
} int itemProcessed = 0;
int loopCnt = 0;
do
{
List<Task> taskList = new List<Task>();
for (int i = 0; i < maxConcurrent; i++)
{
taskList.Add(Task.Factory.StartNew((object obj) =>
{
int j = (int)obj;
try
{
if (loopCnt * maxConcurrent + j < numberOfUsers)
{
WriteLog(users[loopCnt * maxConcurrent + j]);
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("{0} encounter error :{1}", users[loopCnt * maxConcurrent + j],ex.Message ));
}
}
,i));
Interlocked.Increment(ref itemProcessed);
}
Task.WaitAll(taskList.ToArray());
loopCnt++;
} while (itemProcessed < numberOfUsers); Console.WriteLine("Will End soon!");
Thread.Sleep(500000000); }
catch (Exception ex)
{
Console.WriteLine(string.Format("Time {0}:{1}",DateTime.Now, ex.Message));
Thread.Sleep(500000000);
}
}
7.每次最多3个user一起干活
!wrong
static void Main(string[] args)
{ ThreadPool.SetMaxThreads(1, 100); int numberOfUsers = 10;
int maxWorkUsers = 3;
var users = new string[numberOfUsers];
for (int i = 0; i < numberOfUsers; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
} var options = new ParallelOptions();
options.MaxDegreeOfParallelism = maxWorkUsers;
Parallel.ForEach(users, options,
(user) =>
{
WriteLog(user);
});
Thread.Sleep(500000000);
}
correct
static void Main(string[] args)
{
try
{
int numberOfUsers = 10;
var users = new string[numberOfUsers];
for (int i = 0; i < numberOfUsers; i++)
{
users[i] = string.Format("LoadTest{0}", i + 1);
} Action[] aArr = new Action[numberOfUsers];
int j = 0 ;
for (int i = 0; i < numberOfUsers; i++){
aArr[i] = new Action(() => WriteLog(users[j++]));
} System.Threading.Tasks.ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = 3; try
{
System.Threading.Tasks.Parallel.Invoke(po, aArr);
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
{
if (v is TaskCanceledException)
Console.WriteLine(" TaskCanceledException: Task {0}",
((TaskCanceledException)v).Task.Id);
else
Console.WriteLine(" Exception: {0}", v.Message);
} }
Console.WriteLine("Will End soon!");
Thread.Sleep(500000000); }
catch (Exception ex)
{
Console.WriteLine(string.Format("Time {0}:{1}",DateTime.Now, ex.Message));
Thread.Sleep(500000000);
}
} private static void WriteLog(string userName)
{
Console.WriteLine(string.Format("Begin Time {0}:ProcessId {2} ThreadId {3} {1}", DateTime.Now, userName, System.Diagnostics.Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(5000);
if (userName == "LoadTest2")
{
Thread.Sleep(5000);
throw new Exception("Lazy!");
}
Console.WriteLine(string.Format("End Time {0}:ProcessId {2} ThreadId {3} {1}", DateTime.Now, userName, System.Diagnostics.Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId));
}
8.多線程改變某值
private static List<string> testList = new List<string>();
private static void AddList(string name)
{
testList.Add(name);
} static void test2()
{ int threadcount = 10;
List<Thread> threads = new List<Thread>();
for (int i = 0; i < threadcount; i++)
{
Thread t = new Thread(delegate(object parameter)
{
EmpServiceDataContext db = new EmpServiceDataContext();
int _i = (int)parameter;
int index = 0;
for( int k = 0 ; k < 20000 ; k++)
{
if (index % threadcount == _i)
{
try
{
AddList("Thread" + k);
}
catch (Exception ex)
{
}
}
index++;
}
});
t.Name = string.Format("SendEmailThread_{0}", i);
threads.Add(t);
t.Start(i);
}
foreach (Thread t in threads)
{
t.Join();
}
} Task t = Task.Factory.StartNew(() => test2());
t.Wait();
9.volatile 和 Interlocked
http://baike.baidu.com/view/608706.htm?fr=aladdin
1). 并行设备的硬件寄存器(如:状态寄存器)
2). 一个中断服务子程序中会访问到的非自动变量(Non-automatic variables)
3). 多线程应用中被几个任务共享的变量
Interlocked.Decrement(ref JOB_COUNT);
10. ThreadStartStop
如何:创建和终止线程(C# 编程指南)
http://msdn.microsoft.com/zh-cn/library/7a2f3ay4(VS.80).aspx
public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
} public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork); // Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread..."); // Loop until worker thread activates.
while (!workerThread.IsAlive); // Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1); // Request that the worker thread stop itself:
workerObject.RequestStop(); // Use the Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("main thread: Worker thread has terminated.");
}
}
Task , Thread 学习的更多相关文章
- Task类学习教程—组合任务ContinueWith
Task类学习教程-组合任务.ContinueWith 一.简介 通过任务,可以指定在任务完成之后,应开始运行之后另一个特定任务.ContinueWith是Task根据其自身状况,决定后续应该作何操作 ...
- Reduce Task的学习笔记
MapReduce五大过程已经分析过半了.上次分析完Map的过程,着实花费了我的非常多时间.只是收获非常大,值得了额,这次用相同的方法分析完了Reduce的过程,也算是彻底摸透了MapReduce思想 ...
- InnoDB master thread学习
很久很久没有写博客了,工作比较忙,也没什么时间学习了,恰逢国庆放假,安心的学习一下,其实只是把之前学习过的知识再温习了一下而已.InnoDB 有众多的线程,其中非常核心的就是master thread ...
- thread学习笔记--BackgroundWorker 类
背景: 在 WinForms 中,有时要执行耗时的操作,比如统计某个磁盘分区的文件夹或者文件数目,如果分区很大或者文件过多的话,处理不好就会造成“假死”的情况,或者报“线程间操作无效”的异常,或者在该 ...
- Thread学习
1.定义 2.作用 3.和进程的比较 4.多线程(multithreading)的优点和缺陷 5.调度(scheduling) 6.线程相关概念 定义 线程就是最小的可编程指令序列,是进程的子集.一个 ...
- c++11: <thread>学习
<thread>头文件中包含thread类与this_thread命名空间,下面逐一介绍. thread类 1. 构造函数 (1)默认构造函数 thread() noexcept; 默认构 ...
- Boost Thread学习笔记五
多线程编程中还有一个重要的概念:Thread Local Store(TLS,线程局部存储),在boost中,TLS也被称作TSS,Thread Specific Storage.boost::thr ...
- Boost Thread学习笔记四
barrierbarrier类的接口定义如下: 1 class barrier : private boost::noncopyable // Exposition only 2 { 3 pub ...
- Boost Thread学习笔记三
下面先对condition_impl进行简要分析.condition_impl在其构造函数中会创建两个Semaphore(信号量):m_gate.m_queue,及一个Mutex(互斥体,跟boost ...
随机推荐
- review代码,需要做些什么???
有一种习惯,叫看代码找问题:有另一种习惯,叫不看代码很不习惯. 这,矛盾,处处不在! review代码(code diff升级)到底可以做些什么?该做些什么? 1.整体代码风格是否贴切已有框架的设计风 ...
- c++:论如何成功把自己搞懵【二叉树特辑①】(不定期更新)
并不正经的前言 以前我这个小白看OI的书,老觉得有些东西很高端(看不懂的自然就很高端[滑稽]):什么栈啊,位运算啊,二叉树啊.有些东西我学了之后也很迷糊(真的不是因为傻?),做题的时候总是可以把自己搞 ...
- fiddler笔记:web session窗口介绍
1.web session列表的含义:(从左到右) # fiddler通过session生成的ID. Result 响应状态码. Host 接收请求的服务器的主机名和端口号. URL 请求资源的位置. ...
- 基于白名单的Payload
利用 Msiexec 命令DLL反弹 Msiexec是Windows Installer的一部分.用于安装Windows Installer安装包(MSI),一般在运行Microsoft Update ...
- 使用XPath爬取网页数据
我们以我的博客为例,来爬取我所有写过的博客的标题. 首先,打开我的博客页面,右键“检查”开始进行网页分析.我们选中博客标题,再次右键“检查”即可找到标题相应的位置,我们继续点击右键,选择Copy,再点 ...
- UML中的类图
模型 类 接口 关系 关联关系 描述了类的结构之间的关系.具有方向.名字.角色和多重性等信息.一般的关联关系语义较弱.也有两种语义较强,分别是聚合与组合 聚合 特殊关联关系,指明一个聚集(整体)和组成 ...
- C++ STL 之 deque
deque 和 vector 的最大差异? 一在于 deque 允许常数时间内对头端进行元素插入和删除操作. 二在于 deque 没有容量的概念,因为它是动态的以分段的连续空间组合而成,随时可以增加一 ...
- Redis的最常见面试问题
Redis的那些最常见面试问题[转] 1.什么是redis? Redis 是一个基于内存的高性能key-value数据库. 2.Reids的特点 Redis本质上是一个Key-Value类型的内存数据 ...
- shell 判断月末日期
有一个需求,根据输入的时间段,在这个时间段中的是月末的日期执行脚本 解决如下: #!/bin/bashif [ -z $1 ]thenecho "请输入年月日8位开始日期"exit ...
- 【Git】二、文件的提交与查看
提要 //添加git跟踪文件,stage操作 $git add readme.txt //提交到本地分支 $git commit -m xxx //查看当前git工作状态,可以看到未跟踪文件,已跟踪未 ...