生活随笔
收集整理的這篇文章主要介紹了
异步 Thread
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Threads
最早的版本,微軟推薦不要再使用Thread了
thread不支持帶返回值的方法
本身也沒有線程回調(diào),但是可以自己做一個(gè)
private void btnThreads_Click(
object sender, EventArgs e){Stopwatch watch =
new Stopwatch();watch.Start();Console.WriteLine();Console.WriteLine("********************btnThread_Click Start 主線程id={0}********************", Thread.CurrentThread.ManagedThreadId);List<Thread> threadList =
new List<Thread>
();for (
int i =
0; i <
5; i++
){ParameterizedThreadStart method = o =>
TestThreadWithoutReturn(o.ToString());Thread thread =
new Thread(method);
//1. 默認(rèn)前臺(tái)線程:程序退出后,計(jì)算任務(wù)會(huì)繼續(xù)thread.IsBackground =
true;
//2. 后臺(tái)線程:程序退出,計(jì)算理解結(jié)束thread.Start(
string.Format(
"btnThread_Click_{0}", i));threadList.Add(thread);}//for (int i = 0; i < 5; i++)//{// //使用Thread完成多線程回調(diào)// int b = i;// ParameterizedThreadStart method = o => TestThreadWithoutReturn(o.ToString());//要多線程執(zhí)行的任務(wù)// Action callback = () => Console.WriteLine("回調(diào) btnAsync_Click_{0}",b);//回調(diào)執(zhí)行的任務(wù)// ThreadStart methodAll = new ThreadStart(() =>// {// method.Invoke(string.Format("btnAsync_Click_{0}", b));// callback.Invoke();// });// Thread thread = new Thread(methodAll);// thread.Start();// threadList.Add(thread);//}foreach (
var item
in threadList ){item.Join(); //主線程等待
}watch.Stop();Console.WriteLine("********************btnThread_Click End 主線程id={0} {1}********************", Thread.CurrentThread.ManagedThreadId, watch.ElapsedMilliseconds);Console.WriteLine();} private void TestThreadWithoutReturn(
string name){Console.WriteLine("TestThread Start Name={2},當(dāng)前線程的id:{0},當(dāng)前時(shí)間為{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString(
"hh:mm:ss:fff"), name);long Sum =
0;for (
int i =
1; i <
999999999; i++
){Sum +=
i;}//Thread.Sleep(2000);Console.WriteLine(
"TestThread End Name={2},當(dāng)前線程的id:{0},當(dāng)前時(shí)間為{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString(
"hh:mm:ss:fff"), name);} ?
轉(zhuǎn)載于:https://www.cnblogs.com/xiao9426926/p/6429530.html
總結(jié)
以上是生活随笔為你收集整理的异步 Thread的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。