110,533
社区成员
发帖
与我相关
我的任务
分享
//委托
public delegate void SetTextCallback(string text);
//显示状态(ListBox)
private void SetText(string text)
{
if (this.listBoxStatus.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBoxStatus.Items.Add(text);
this.listBoxStatus.SelectedIndex = this.listBoxStatus.Items.Count - 1;
}
//你的程序按钮事件
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ThreadStart(MyWorkThread));
thread1.Start();
}
//线程调用的函数
public void MyWorkThread(object p1)
{
//你要干的事
//......
SetText("你要显示的进度");
//......
return;
}
class Program
{
static void Main(string[] args)
{
MyMainThread mainThread = new MyMainThread();
mainThread.Test();
Thread thread = new Thread(new ThreadStart(mainThread.Test));
thread.Start();
while (true)
{
;
}
}
}
class MyMainThread
{
public void Test()
{
MyThreadWrapper wrapper = new MyThreadWrapper(GetDataAfterMyThread);
Thread thread = new Thread(new ThreadStart(wrapper.DoMyThread));
thread.Start();
while (thread.IsAlive)
{
;
}
Thread.CurrentThread.Join(100);
Console.WriteLine("主线程:我接着进行……");
for (int i = 0; i < 10; i++)
{
Thread.CurrentThread.Join(100);
Console.WriteLine("主线程:" + i.ToString());
}
}
void GetDataAfterMyThread(object data)
{
Console.WriteLine(data.ToString());
Console.WriteLine("主线程:收到了子线程的通知!");
}
}
class MyThreadWrapper
{
public delegate void DelegateDoAfterFinish(object data);
DelegateDoAfterFinish DoAfterFinish = null;
public MyThreadWrapper()
{
}
public MyThreadWrapper(DelegateDoAfterFinish d)
{
DoAfterFinish = d;
}
public void DoMyThread()
{
Console.WriteLine("子线程:我正在做些事情!");
Thread.CurrentThread.Join(1000);
if (DoAfterFinish != null)
{
DoAfterFinish("子线程:OK,我做完啦!");
}
}
public void DoMyThread(object i)
{
Console.WriteLine("子线程:我正在做些事情!");
Thread.CurrentThread.Join(1000);
i = 100;
if (DoAfterFinish != null)
{
DoAfterFinish("子线程:OK,我做完啦!" + i.ToString());
}
}
}
class Program
{
static void Main(string[] args)
{
MyMainThread mainThread = new MyMainThread();
mainThread.Test();
//Thread thread = new Thread(new ThreadStart(mainThread.Test));
//thread.Start();
MyThreadDemo domethread = new MyThreadDemo();
domethread.Run();
while (true)
{
;
}
}
}
class MyMainThread
{
public void Test()
{
MyThreadWrapper wrapper = new MyThreadWrapper(GetDataAfterMyThread);
Thread thread = new Thread(new ThreadStart(wrapper.DoMyThread));
thread.Start();
while (thread.IsAlive)
{
;
}
Thread.CurrentThread.Join(100);
Console.WriteLine("主线程:我接着进行……");
for (int i = 0; i < 10; i++)
{
Thread.CurrentThread.Join(100);
Console.WriteLine("主线程:" + i.ToString());
}
}
void GetDataAfterMyThread(object data)
{
Console.WriteLine(data.ToString());
Console.WriteLine("主线程:收到了子线程的通知!");
}
}