关于多线程操作的问题

chuzhongbiyewenhua 2010-07-30 01:43:45
一个登录程序,连接数据库的部分可能要几秒时间,怎么程序在这段时间内有个一个等待的画面,等连接上了,出了结果了再把这画面取消。谢谢大家。
...全文
83 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuxiangq 2010-07-30
  • 打赏
  • 举报
回复
学习了
daone 2010-07-30
  • 打赏
  • 举报
回复
新建个类就是等待的窗口

public partial class SplashFrm : Form
{
public SplashFrm()
{
InitializeComponent();
}
private string _StatusInfo = "";

//开始登陆前的加载信息
public string StatusInfo
{
set
{
_StatusInfo = value;
ChangeStatusText();
}
get
{
return _StatusInfo;
}
}

public void ChangeStatusText()
{
try
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.ChangeStatusText));
return;
}

this.lbStatus.Text = _StatusInfo;
}
catch (Exception e)
{
throw e;
}
}
}

对应的一个线程操作类


public class Splash
{
//声明加载页
static SplashFrm MySplashForm = null;
//声明加载线程
static Thread MySplashThread = null;

static void ShowThread()
{
MySplashForm = new SplashFrm();
Application.Run(MySplashForm);
}
/// <summary>
/// 显示加载页
/// </summary>
static public void Show()
{
if (MySplashThread != null)
return;

MySplashThread = new Thread(new ThreadStart(Splash.ShowThread));
MySplashThread.IsBackground = true;
MySplashThread.SetApartmentState(ApartmentState.STA);
MySplashThread.Start();
}
/// <summary>
/// 关闭加载页
/// </summary>
static public void Close()
{
if (MySplashThread == null) return;
if (MySplashForm == null) return;

try
{
MySplashForm.Invoke(new MethodInvoker(MySplashForm.Close));
}
catch (Exception)
{
}
MySplashThread = null;
MySplashForm = null;
}
/// <summary>
/// 加载页状态
/// </summary>
static public string Status
{
set
{
if (MySplashForm == null)
{
return;
}

MySplashForm.StatusInfo = value;

}
get
{
if (MySplashForm == null)
{
throw new InvalidOperationException("Splash Form not on screen");
}
return MySplashForm.StatusInfo;
}
}
}


最后main函数里

int intervalTime = 1200;
//显示加载页(新线程)
Login.Splash.Show();

Login.Splash.Status = "状态:正在加载配置文件。。。";
Thread.Sleep(intervalTime);
loadConfig();
Thread.Sleep(intervalTime);

Login.Splash.Status = "状态:正在测试连接数据库。。。";
Thread.Sleep(intervalTime);
ConnectDataBase();
Thread.Sleep(intervalTime);
//关闭加载页
Login.Splash.Close();
兔子-顾问 2010-07-30
  • 打赏
  • 举报
回复
Form waitForm = null;
new Thread((ThreadStart)delegate
{
waitForm = new Form();
Application.Run(waitForm);
}).Start();
//执行你的操作
waitForm.Invoke((EventHandler)delegate { waitForm.Close(); });
mawei0313 2010-07-30
  • 打赏
  • 举报
回复
mark
healer_kx 2010-07-30
  • 打赏
  • 举报
回复
这个是线程比较基本的用法。。。 。。。

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧