代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
CSharp
】
线程进程总结(线程调用带参数的方法)
作者:
Dezai.CN
/ 发布于
2012/10/25
/
688
线程进程总结(线程调用带参数的方法)
<div>新建一个线程,执行一个无参无返回值的方法。</div> <div>/// <summary></div> <div>/// 线程调用的方法,无参无返回值</div> <div>/// </summary></div> <div>private void ThreadMethod()</div> <div>{ } <div>启动线程:</div> <div>using System.Threading;</div> <div>ThreadStart threadStart = new ThreadStart(ThreadMethod);</div> <div>Thread thread = new Thread(threadStart);</div> <div>thread.Start();</div> <div>thread.Abort();</div> <div>如果需要执行带参数的线程:</div> <div>msdn中推荐的方法是间接调用</div> <div>class thd</div> <div>{</div> <div> int x;</div> <div> int y;</div> <div> public thd(int xx, int yy){x=xx;y=yy;} <div> public void thstart(){ start(x, y);} <div> public void start(int a, int b){...} <div></div> <div>} <div>thd t = new thd(3,4);</div> <div>TheadStart myd = new TheadStart(t.thstart);</div> <div>在 .NET Framework 2.0 版中,要实现线程调用带参数的方法有两种办法。</div> <div></div> <div>第一种:使用ParameterizedThreadStart。</div> <div></div> <div>调用 System.Threading.Thread.Start(System.Object) 重载方法时将包含数据的对象传递给线程。</div> <div></div> <div>使用 ParameterizedThreadStart 委托不是传递数据的类型安全的方法,因为 System.Threading.Thread.Start(System.Object) 方法重载接受任何对象。</div> <div></div> <div>这种方法不推荐使用,故在此不做详细介绍,具体用法参见:http://msdn2.microsoft.com/zh-cn/library/system.threading.parameterizedthreadstart(VS.80).aspx</div> <div></div> <div>ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ThreadMethod);</div> <div>Thread myThread = new Thread(ParStart);</div> <div>object o = "hello";</div> <div>myThread.Start(o);</div> <div></div> <div>//ThreadMethod如下:</div> <div>public void ThreadMethod(object ParObject)</div> <div>{</div> <div> //程序代码</div> <div>} <div>复制代码</div> <div></div> <div></div> <div>第二种:将线程执行的方法和参数都封装到一个类里面。通过实例化该类,方法就可以调用属性来实现间接的类型安全地传递参数。</div> <div></div> <div>具体代码如下(本示例来自MSDN)</div> <div></div> <div>using System;</div> <div>using System.Threading;</div> <div></div> <div>//ThreadWithState 类里包含了将要执行的任务以及执行任务的方法</div> <div>public class ThreadWithState {</div> <div> //要用到的属性,也就是我们要传递的参数</div> <div> private string boilerplate;</div> <div> private int value;</div> <div></div> <div> //包含参数的构造函数</div> <div> public ThreadWithState(string text, int number)</div> <div> {</div> <div> boilerplate = text;</div> <div> value = number;</div> <div> } <div></div> <div> //要丢给线程执行的方法,本处无返回类型就是为了能让ThreadStart来调用</div> <div> public void ThreadProc()</div> <div> {</div> <div> //这里就是要执行的任务,本处只显示一下传入的参数</div> <div> Console.WriteLine(boilerplate, value);</div> <div> } <div>} <div></div> <div>//用来调用上面方法的类,是本例执行的入口</div> <div>public class Example {</div> <div> public static void Main()</div> <div> {</div> <div> //实例化ThreadWithState类,为线程提供参数</div> <div> ThreadWithState tws = new ThreadWithState(</div> <div> "This report displays the number {0}.", 42);</div> <div></div> <div> // 创建执行任务的线程,并执行</div> <div> Thread t = new Thread(new ThreadStart(tws.ThreadProc));</div> <div> t.Start();</div> <div> Console.WriteLine("Main thread does some work, then waits.");</div> <div> t.Join();</div> <div> Console.WriteLine(</div> <div> "Independent task has completed; main thread ends."); </div> <div> } <div>} <div>复制代码</div> <div></div> <div></div> <div>============================================================================</div> <div></div> <div>方法一:</div> <div>在VS2003中,也不能直接访问,参看 </div> <div>一般来说,直接在子线程中对窗体上的控件操作是会出现异常,这是由于子线程和运行窗体的线程是不同的空间,因此想要在子线程来操作窗体上的控件,是不可能 简单的通过控件对象名来操作,但不是说不能进行操作,微软提供了Invoke的方法,其作用就是让子线程告诉窗体线程来完成相应的控件操作。 </div> <div></div> <div>现在用一个用线程控制的进程条来说明,大致的步骤如下: </div> <div></div> <div>1.创建Invoke函数,大致如下: </div> <div>/// <summary> </div> <div>/// Delegate function be invoked by main thread </div> <div>/// </summary> </div> <div>private void InvokeFun() </div> <div>{ </div> <div> if(prgBar.Value< 100) </div> <div> prgBar.Value = prgBar.Value + 1; </div> <div>} </div> <div></div> <div>2.子线程入口函数: </div> <div>/// <summary> </div> <div>/// Thread function interface </div> <div>/// </summary> </div> <div>private void ThreadFun() </div> <div>{ </div> <div> // Create invoke method by specific function</div> <div> MethodInvoker mi = new MethodInvoker(this.InvokeFun); </div> <div></div> <div> for(int i=0; i<100; i++) </div> <div> { </div> <div> this.BeginInvoke(mi); </div> <div> Thread.Sleep(100); </div> <div> } </div> <div>} <div></div> <div>3.创建子线程: </div> <div>Thread thdProcess = new Thread(new ThreadStart(ThreadFun)); </div> <div>thdProcess.Start(); </div> <div></div> <div>备注: </div> <div> using System.Threading; </div> <div> private System.Windows.Forms.ProgressBar prgBar; </div> <div></div> <div>方法二:</div> <div>加入该句:Control.CheckForIllegalCrossThreadCalls = False 取消线线程安全保护模式!</div> <div></div> <div>方法三:带参数</div> <div>使用类、类的方法或类的属性都可以向线程传递参数:</div> <div>public class UrlDownloader</div> <div>{</div> <div> string url;</div> <div></div> <div> public UrlDownloader (string url)</div> <div> {</div> <div> this.url = url;</div> <div> } <div></div> <div> public void Download()</div> <div> {</div> <div> WebClient wc = new WebClient();</div> <div> Console.WriteLine("Downloading " + url); </div> <div> byte[] buffer = wc.DownloadData (url);</div> <div> string download = Encoding.ASCII.GetString(buffer);</div> <div> Console.WriteLine(download);</div> <div> Console.WriteLine("Download successful.");</div> <div> </div> <div> //这里你可以将download进行保存等处理......</div> <div> } <div>} <div></div> <div>[... 在另一个类中使用它们...]</div> <div> </div> <div>UrlDownloader downloader = new UrlDownloader (yourUrl);</div> <div>new Thread (new ThreadStart (downloader.Download)).Start();</div> <div></div> <div>注意参数是如何传递的。</div> <div></div> <div>方法四:带参数</div> <div>ThreadStart starter = delegate { Download(yourUrl); };</div> <div>new Thread(starter).Start();</div> <div></div> <div>//使用线程池</div> <div>WaitCallback callback = delegate (object state) { Download ((string)state); };</div> <div>ThreadPool.QueueUserWorkItem (callback, yourUrl);</div> <div></div> <div>方法五:带参数</div> <div>Thread t = new Thread (new ParameterizedThreadStart(DownloadUrl));</div> <div>t.Start (myUrl);</div> <div>static void DownloadUrl(object url)</div> <div>{</div> <div> // ....</div> <div>} <div></div> <div>C#进程操作</div> <div>总结一下进程的新建和终止的操作过程。看代码:</div> <div></div> <div> public int CallPhoneExe(string arg) //arg为进程的命令行参数</div> <div> { WaitHandle[] waits =new WaitHandle[2]; //定义两个WaitHandle值,用以控制进程的执行过程</div> <div> waits[0] = HSTOP; //AutoResetEvent HSTOP = new AutoResetEvent(false);</div> <div> waits[1] = GlobalStop;//AutoResetEvent GlobalStop = new AutoResetEvent(false);</div> <div> int iReturn=0;</div> <div> Process p = new Process();//新建一个进程</div> <div> p.StartInfo.Arguments = arg; //进程的命令行参数</div> <div> p.StartInfo.FileName = filepath;//进程启动路径</div> <div> </div> <div> p.StartInfo.CreateNoWindow = true;//不显示新进程的窗口</div> <div> p.StartInfo.RedirectStandardOutput = true;//输出重定向</div> <div> p.StartInfo.RedirectStandardError = true; //Redirect the error ouput!</div> <div> p.StartInfo.UseShellExecute = false;</div> <div> p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;</div> <div></div> <div> p.EnableRaisingEvents = true;</div> <div> p.Exited += new EventHandler(p_Exited); //进程自然结束后启动p—Exited事件</div> <div> p.OutputDataReceived += new DataReceivedEventHandler(ChangeOutput);//进程有输出时,启动ChangeOutPut函数 </div> <div></div> <div> p.Start();//进程启动</div> <div> p.BeginOutputReadLine();</div> <div></div> <div> int hstop = WaitHandle.WaitAny(waits);//启动线程暂停,知道WaitHandle中传来有效信号</div> <div> switch (hstop)//判断信号是又哪个</div> <div> {</div> <div> case 0: //进程自然结束</div> <div> if (p.WaitForExit(2000))</div> <div> iReturn = p.ExitCode; //获取进程的返回值</div> <div> else</div> <div> {</div> <div> CloseProcess();</div> <div> iReturn = -2;</div> <div> } <div> break;</div> <div> case 1: //进程被迫结束</div> <div> p.Kill();//杀掉进程</div> <div> if (!p.HasExited)</div> <div> { </div> <div> p.Kill();</div> <div> } </div> <div> iReturn = -3;</div> <div> break;</div> <div> } <div> HSTOP.Reset(); //HSTOP复位,这个变量指示进程自然结束,每次结束后都得自然复位 </div> <div> p.Close(); //创建的p关闭</div> <div> return iReturn; </div> <div> } <div></div> <div></div> <div> private void p_Exited(object sender, EventArgs e)</div> <div> {</div> <div> HSTOP.Set();</div> <div> } <div></div> <div>//输出重定向函数</div> <div>private void ChangeOutput(object sendingProcess, DataReceivedEventArgs outLine)</div> <div> {</div> <div> if (!String.IsNullOrEmpty(outLine.Data)) //字符串不为空时</div> <div> MainForm.FireWriteText(outLine.Data,false);//将进程的输出信息转移</div> <div> } <div></div> <div></div> <div></div> <div>上面总结了新建一个进程的步骤。结束进程的方法可以采用在主线程中将GlobalStop变量设置有效信号,这样就会调用p.kill()</div> <div></div> <div>在系统的所有进程中找寻指定进程的方法:</div> <div></div> <div> foreach (Process p in Process.GetProcesses())</div> <div> {</div> <div> if (p.ProcessName == "specialProcess")</div> <div> {</div> <div> //do smth</div> <div></div> <div> } <div> </div> <div> }
试试其它关键字
线程进程
同语言下
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
Dezai.CN
贡献的其它代码
(
4037
)
.
多线程Socket服务器模块
.
生成随机密码
.
清除浮动样式
.
弹出窗口居中
.
抓取url的函数
.
使用base HTTP验证
.
div模拟iframe嵌入效果
.
通过header转向的方法
.
Session操作类
.
执行sqlite输入插入操作后获得自动编号的ID
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3