新建线程方法
//建立事件
void tianqi()
{
//天气预报
//string url = @"tianqiapi.com/api.php?style=tk&skin=sogou";//天气预报的网页地址
//webBrowser1.Url = new Uri("http://" + url);
//webBrowser1.ScrollBarsEnabled = false;
webBrowser1.Navigate("http://tianqiapi.com/api.php?style=tk&skin=sogou");//绑定网址
//webBrowser1.ScriptErrorsSuppressed = false;
webBrowser1.ScrollBarsEnabled = false;//不显示滚动条
}
//创建线程
ThreadStart threadStart2 = new ThreadStart(tianqi);//通过ThreadStart委托告诉子线程执行什么方法
Thread thread2 = new Thread(threadStart2);
thread2.Start();//启动新线程
使其他线程可以访问主线程窗体上的控件
Control.CheckForIllegalCrossThreadCalls = false;//去掉线程访问主线程UI控件的安全检查,使多线程可以访问winform上的控件
控制方法的执行时间,超时则强制退出方法执行
static void Main(string[] args)
{
//try the five second method with a 6 second timeout
CallWithTimeout(FiveSecondMethod, 6000);
//try the five second method with a 4 second timeout
//this will throw a timeout exception
CallWithTimeout(FiveSecondMethod, 4000);
}
static void FiveSecondMethod()
{
Thread.Sleep(5000);
}
//用来写超时获取则结束线程,action是事件,int是毫秒
static void CallWithTimeout(Action action, int timeoutMilliseconds)
{
Thread threadToKill = null;
Action wrappedAction = () =>
{
threadToKill = Thread.CurrentThread;
action();
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
wrappedAction.EndInvoke(result);
}
else
{
threadToKill.Abort();
//throw new TimeoutException();
}
}