多线程---Thread理解(二)
一、Thread
NetFramework 1.0 1.1 Thread是最初版本,功能非常强大,唯一的前台线程。在System.Threading 命名空间下,包含了创建和操作线程。
二、启用线程
//ThreadStart 没有参数的委托
ThreadStart threadStart = () => Todo("ThreadMethod");
//Thread 接收一个 ThreadStart 对象的参数
Thread thread = new Thread(threadStart);
//开启线程,执行委托
thread.Start();
//ParameterizedThreadStart 带参数的委托
ParameterizedThreadStart parameterizedThreadStart = s => Todo("ThreadMethod");
//Thread 接收一个 ThreadStart 对象的参数
Thread thread = new Thread(parameterizedThreadStart);
//开启线程,执行委托
thread.Start("123");
三、暂停线程
thread.Suspend();
四、恢复暂停
thread.Resume();
五、挂起线程
thread.Abort();
六、等待线程执行完后再执行
//1.判断线程是否已经停止,如果线程已经停止,继续执行
while (thread.ThreadState!=ThreadState.Stopped)
{
Thread.Sleep(200);
}
//2. join方法等待
thread.Join();
七、优先级 Highest:最高优先级 默认为:Normal
thread.Priority = ThreadPriority.Highest;
八、设置线程为前台线程/后台线程
thread.IsBackground = false; //前台线程 进程关闭之后,线程必须执行完了再退出
thread.IsBackground = true; //后台线程 进程关闭之后,线程也同时退出
九、回调,启动子线程执行动作A,不阻塞,A执行完了之后,子线程在执行动作B
private void ThreadCallBack(ThreadStart threadStart, Action action)
{
ThreadStart start = new ThreadStart(() =>
{
threadStart.Invoke();
action.Invoke();
});
new Thread(start).Start();
}
//调用回调方法
ThreadStart threadStart = new ThreadStart(() =>
{
Thread.Sleep(2000);
Console.WriteLine("threadStart 开始执行");
});
Action callBack = () =>
{
Console.WriteLine("子线程执行完了,在执行回调....");
};
ThreadCallBack(threadStart, callBack);
十、委托异步方法,并且返回执行的结果
private Func<T> ThreadReturn<T>(Func<T> func)
{
T t = default(T);
ThreadStart threadStart = () =>
{
t = func.Invoke();
};
var thread = new Thread(threadStart);
thread.Start();
return new Func<T>(() =>
{
thread.Join();
return t;
});
}
//调用
ThreadStart threadStart = new ThreadStart(() =>
{
Thread.Sleep(2000);
Console.WriteLine("threadStart 开始执行");
});
Func<int> func = () =>
{
Thread.Sleep(2000);
return DateTime.Now.Year;
};
var threadReturn = ThreadReturn(func);
var result = threadReturn.Invoke();
Console.WriteLine($"result={result}");
private void Todo(string name)
{
Console.WriteLine($"Todo 方法开始执行....");
long result = 0;
for (int i = 0; i < 100000; i++)
{
result += i;
}
Thread.Sleep(500);
Console.WriteLine($"Todo方法执行的结果:{result},名称{name},ManagedThreadId:{Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine($"Todo 方法结束执行....");
}
将来的你,一定会感谢现在努力的自己!