生活随笔
收集整理的這篇文章主要介紹了
异步 Thread
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Threads
最早的版本,微軟推薦不要再使用Thread了
thread不支持帶返回值的方法
本身也沒有線程回調,但是可以自己做一個
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. 默認前臺線程:程序退出后,計算任務會繼續thread.IsBackground =
true;
//2. 后臺線程:程序退出,計算理解結束thread.Start(
string.Format(
"btnThread_Click_{0}", i));threadList.Add(thread);}//for (int i = 0; i < 5; i++)//{// //使用Thread完成多線程回調// int b = i;// ParameterizedThreadStart method = o => TestThreadWithoutReturn(o.ToString());//要多線程執行的任務// Action callback = () => Console.WriteLine("回調 btnAsync_Click_{0}",b);//回調執行的任務// 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},當前線程的id:{0},當前時間為{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},當前線程的id:{0},當前時間為{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString(
"hh:mm:ss:fff"), name);} ?
轉載于:https://www.cnblogs.com/xiao9426926/p/6429530.html
總結
以上是生活随笔為你收集整理的异步 Thread的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。