学习笔记——线程 Thread

时间:2021-12-14 19:47:37

Thread是.net1.0 1.1时出现的

主要了解线程等待、回调、前后台线程区别

1.实例

//定义:public delegate void ThreadStart();

ThreadStart threadStart = new ThreadStart(() =>

{

Thread.Sleep(5000);

this.DoSomethingLong("btnThreads_Click");

});

Thread thread = new Thread(threadStart);

//thread.IsBackground = true;//变成后台线程

thread.Start();//默认是前台线程,UI线程退出后,还会继续执行完;后台线程就直接退出了

 2.等待(如果线程执行完毕,dosomething())

while (thread.ThreadState != System.Threading.ThreadState.Running)

{

dosomething()

}

3.获取线程执行后的返回值

/// <summary>

/// 带返回值的

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="funcT"></param>

/// <returns></returns>

private Func<T> ThreadWithReturn<T>(Func<T> funcT)

{

T t = default(T);

ThreadStart startNew = new ThreadStart(

() =>

{

t = funcT.Invoke();

});

Thread thread = new Thread(startNew);

thread.Start();

return new Func<T>(() =>

{

thread.Join();//线程执行完才返回t.(主线程会等待子线程完成)

return t;

});

}

调用方法获取返回值

Func<int> func = this.ThreadWithReturn(() =>//begininvoke

{

Thread.Sleep(2000);

Console.WriteLine($"这里是ThreadStart {Thread.CurrentThread.ManagedThreadId.ToString("00")}");

return 12345;

});

Console.WriteLine("已经执行到这里了。。。");

int iResult = func.Invoke();//endinvoke

4.回调

/// <summary>

/// 基于Thread封装支持回调

/// BeginInvoke的回调

/// </summary>

/// <param name="threadStart"></param>

/// <param name="callback"></param>

private void ThreadWithCallback(ThreadStart threadStart, Action callback)

{

ThreadStart startNew = new ThreadStart(

() =>

{

threadStart();

callback.Invoke();

});

Thread thread = new Thread(startNew);

thread.Start();

}

//委托的异步调用 测试:ThreadWithCallback

this.ThreadWithCallback(() =>

{

Thread.Sleep(2000);

Console.WriteLine($"这里是ThreadStart {Thread.CurrentThread.ManagedThreadId.ToString("00")}");

}

, () =>

{

Thread.Sleep(2000);

Console.WriteLine($"这里是callback {Thread.CurrentThread.ManagedThreadId.ToString("00")}");

});

参考资料:http://www.cnblogs.com/lvcy/archive/2012/06/16/2551539.html