C#多线程的回调没Java的handler直接,不过比C++好多了;回调用代理delegate。需要注意的是回调函数不是在原线程中调用的,而是在创建的工作线程中调用,OpenGL和Direct3D一样所有涉及到上下文和设备的语句需要在同一个线程中调用,不然就会失败。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace conThreadCallBack
{
class Program
{
static void Main(string[] args)
{
Program pro = new Program();
ThreadWithState tws = new ThreadWithState("你好吗?", pro.ResultCallBack);
Thread th = new Thread(tws.ThreadProc);
th.Start();
Console.WriteLine("主线程: 开始执行, 等待新线程 ...");
th.Join(); //等待线程 th 执行完毕后, 再执行主线程中的后面的语句.
Console.WriteLine("主线程: 新线程执行完毕.");
Console.ReadKey();
}// 回调方法
private void ResultCallBack(string message)
{
Console.WriteLine("主线程: 传回的消息: {0}", message);
}
}
public delegate void CallBackDelegate(string message);
public class ThreadWithState
{
private string Message;
// 回调委托
private CallBackDelegate callback;
// 构造函数
public ThreadWithState(string message, CallBackDelegate callbackDelegate)
{
this.Message = message;
this.callback = callbackDelegate;
}
// 线程方法
public void ThreadProc()
{
Console.WriteLine("新线程: 开始执行 ..");
Console.WriteLine("新线程: 传入的消息: {0}", Message);
if (callback != null) callback("谢谢, 我很好呀!"); // 通过委托, 将数据回传给回调函数
}
}
}
本文介绍了一个使用C#实现多线程回调的例子,展示了如何利用委托进行线程间的数据传递,并强调了OpenGL和Direct3D等图形库在多线程环境下使用时的注意事项。
378

被折叠的 条评论
为什么被折叠?



