发送代码: var imgFile = Request.Files["imgFile"]; if (imgFile == null) return; var img = Image.FromStream(imgFile.InputStream); var ms = new MemoryStream(); img.Save(ms,ImageFormat.Jpeg); var data = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(data, 0, Convert.ToInt32(ms.Length)); ms.Dispose(); var fileName = imgFile.FileName; var fileType = imgFile.ContentType; var fileSize = data.Length.ToString(); var myRequest = WebRequest.Create(Common.ImgUrl + "/upload/UploadImg.aspx"); myRequest.Method = "POST"; myRequest.ContentType = fileType; myRequest.ContentLength = data.Length; myRequest.Headers.Add("FileType", Server.UrlEncode(fileType)); myRequest.Headers.Add("FileSize", fileSize); myRequest.Headers.Add("FileName", Server.UrlEncode(fileName)); myRequest.Headers.Add("dir", Server.UrlEncode(Request["dir"])); using (var newStream = myRequest.GetRequestStream()) { // Send the data. newStream.Write(data, 0, data.Length); newStream.Close(); } // Get response var myResponse = myRequest.GetResponse(); […]
View Details//利用InputStream 属性直接从HttpPostedFile对象读取文本内容 System.IO.Stream MyStream; int FileLen; FileLen = file.ContentLength; // 读取文件的 byte[] byte[] bytes = new byte[FileLen]; MyStream = file.InputStream; MyStream.Read(bytes, 0, FileLen); from:http://blog.csdn.net/yyixin/article/details/5336899
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
// 待请求的地址 string url = "http://www.cnblogs.com"; // 创建 WebRequest 对象,WebRequest 是抽象类,定义了请求的规定, // 可以用于各种请求,例如:Http, Ftp 等等。 // HttpWebRequest 是 WebRequest 的派生类,专门用于 Http System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest; // 请求的方式通过 Method 属性设置 ,默认为 GET // 可以将 Method 属性设置为任何 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。 request.Method = "POST"; // 还可以在请求中附带 Cookie // 但是,必须首先创建 Cookie 容器 request.CookieContainer = new System.Net.CookieContainer(); System.Net.Cookie requestCookie = new System.Net.Cookie("Request", "RequestValue","/", "localhost"); request.CookieContainer.Add(requestCookie); Console.WriteLine("请输入请求参数:"); // 输入 POST 的数据. string inputData = Console.ReadLine(); // 拼接成请求参数串,并进行编码,成为字节 string postData = "firstone=" + inputData; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(postData); // 设置请求的参数形式 request.ContentType = "application/x-www-form-urlencoded"; // 设置请求参数的长度. request.ContentLength = byte1.Length; // 取得发向服务器的流 System.IO.Stream newStream = request.GetRequestStream(); // 使用 POST 方法请求的时候,实际的参数通过请求的 Body 部分以流的形式传送 newStream.Write(byte1, 0, byte1.Length); // 完成后,关闭请求流. newStream.Close(); // GetResponse 方法才真的发送请求,等待服务器返回 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); // 首先得到回应的头部,可以知道返回内容的长度或者类型 Console.WriteLine("Content length is {0}", response.ContentLength); Console.WriteLine("Content type is {0}", response.ContentType); // 回应的 Cookie 在 Cookie 容器中 foreach (System.Net.Cookie cookie in response.Cookies) { Console.WriteLine("Name: {0}, Value: {1}", cookie.Name, cookie.Value); } Console.WriteLine(); // 然后可以得到以流的形式表示的回应内容 System.IO.Stream receiveStream = response.GetResponseStream(); // 还可以将字节流包装为高级的字符流,以便于读取文本内容 // 需要注意编码 System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, Encoding.UTF8); Console.WriteLine("Response stream received."); Console.WriteLine(readStream.ReadToEnd()); // 完成后要关闭字符流,字符流底层的字节流将会自动关闭 response.Close(); readStream.Close(); |
from:http://www.cnblogs.com/haogj/archive/2011/06/09/2076708.html
View DetailsAuthor:xuzhihong Create Date:2011-06-03 Descriptions: WinForm程序使用HttpWebRequest实现大文件上传 概述: 通常在WinForm程序中都是采用WebClient方式实现文件上传功能,本身这个方式没有问题,但是当需要上传大文件比如说(300+M)的时候,那么WebClient将会报内存不足异常(Out of Memory Exceptions),究其原因是因为WebClient方式是一次性将整个文件全部读取到本地内存中,然后再以数据流形式发送至服务器。本文将讲述如何采用HttpWebRequest方式每次读取固定大小数据片段(如4KB)发送至服务器,为大文件上传提供解决方案,本文还将详细讲述将如何将“文件上传”功能做为用户自定义控件,实现模块重用。 关键词:HttpWebRequest、WebClient、OutOfMemoryExceptions 解决方案: 开始我在WinForm项目中实现文件上传功能的时候,是采用WebClient(WebClient myWebClient = new WebClient();)方式,这大部分情况都是正确的,但有时候会出现内存不足的异常(Out of Memory Exceptions),经常测试,发现是由于上传大文件的时候才导致这问题。在网上查阅了一下其他网友的解决方案,最后找的发生异常的原因:“WebClient方式是一次性将整个文件全部读取到本地内存中,然后再以数据流形式发送至服务器”,详细请参考:http://blogs.msdn.com/b/johan/archive/2006/11/15/are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx 。按照这个解释,那么大文件上传出现内存不足的异常也就不足为奇了。下面我将讲述如何一步步使用HttpWebRequest方式来实现文件分块上传数据流至服务器。 按照惯例还是先预览一下文件上传最后的效果吧,如下图所示: 界面分为两部分,上面是文件基本信息,下面是文件上传自定义控件,我这里实现的是一个案件上传多个监控视频功能。以下是详细步骤: 第一步:创建用户自定义控件BigFileUpload.xaml 文件上传是一个非常常用的功能,为了所写的程序能非常方便地多次重复使用,我决定将其处理为一个用户自定义控件(UserControl)。 我们先在项目中创建一个FileUpload文件夹,在其目录下新建一个WPF自定义控件文件命名为BigFileUpload.xaml,这样就表示文件上传是一个独立的小模块使用。之所以用WPF自定义控件是因为WPF页面效果好看点,而且我想以后可能大部分C/S程序都会渐渐的由WinForm转向WPF吧,当然创建Window Forms用户控件也是没有问题的。然后我们需要做一个下图效果的页面布局: 前台设计代码如下: <UserControl x:Class="CHVM.FileUpload.BigFileUpload" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="160" Width="480"> <Grid Height="160" Width="480" Background="White"> <Label Height="28" HorizontalAlignment="Left" Margin="16,10,0,0" Name="label1" VerticalAlignment="Top" Width="53">文件</Label> <Label HorizontalAlignment="Left" Margin="15,52,0,80" Name="label2" Width="54">进度</Label> <ProgressBar Height="20" Margin="61,52,116,0" Name="progressBar1" VerticalAlignment="Top" /> <TextBox Height="23" Margin="61,12,116,0" Name="txtBoxFileName" VerticalAlignment="Top" /> <Button Height="23" HorizontalAlignment="Right" Margin="0,10,35,0" Name="BtnBrowse" VerticalAlignment="Top" Width="75" Click="BtnBrowse_Click">浏览…</Button> <Button Height="23" HorizontalAlignment="Right" Margin="0,52,35,0" Name="BtnUpload" VerticalAlignment="Top" Width="75" Click="BtnUpload_Click">上传</Button> <Label HorizontalAlignment="Left" Margin="16,0,0,44" Name="lblState" Width="183" Height="35" […]
View Details一个网站中需要上传一个文件到另一个网站,可以使用HttpWebRequest或者WebClient。 但是WebClient需要首先上传文件到服务器,才能执行发送,不太符合我的需求,这里不再介绍。 通过HttpWebRequest发送的原理: 构建一个HttpWebRequest,通过FileUpload获取要上传的文件,通过字节流发送这个文件,另一个网站接收字节流,保存到服务器。 发送程序: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 //获取要上传的文件信息 byte[]data=fileupload1.FileBytes; stringfileName=fileupload1.FileName; stringfileType=fileupload1.PostedFile.ContentType; stringfileSize=data.Length.ToString(); HttpWebRequest myRequest=(HttpWebRequest)WebRequest.Create("http://localhost:8102/Default.aspx"); myRequest.Method="POST"; myRequest.ContentType=fileType; myRequest.ContentLength=data.Length; myRequest.Headers.Add("FileType",Server.UrlEncode(fileType)); myRequest.Headers.Add("FileSize",fileSize); myRequest.Headers.Add("FileName",Server.UrlEncode(fileName)); using(Stream newStream=myRequest.GetRequestStream()) { // Send the data. newStream.Write(data,0,data.Length); newStream.Close(); } // Get response HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse(); StreamReader reader=newStreamReader(myResponse.GetResponseStream(),Encoding.UTF8); stringcontent=reader.ReadToEnd(); 接收程序: 0 1 2 3 4 5 6 7 8 9 10 stringfileName=Server.UrlDecode(Request.Headers["FileName"].ToString()); stringfileType=Server.UrlDecode(Request.Headers["FileType"].ToString()); intfileSize=int.Parse(Request.Headers["FileSize"].ToString()); byte[]bytes=Request.BinaryRead(fileSize); File.WriteAllBytes(Server.MapPath("~/uploadfiles/"+fileName),bytes); Response.HeaderEncoding=System.Text.Encoding.UTF8; Response.Charset="utf-8"; Response.Write("FileType:"+fileType+";FileName:"+fileName+";FileSize:"+fileSize); FROM:http://blog.bossma.cn/dotnet/asp-net-httpwebrequest-upload-send-file/
View Details早在1979年,Bjarne Stroustrup设计了C++编程语言,并且C++很快成为了无处不在的通用系统编程语言。现在尽管有Java、Javascript、Python、Go,甚至是苹果的Swift和它竞争,但C++依然处于主导编程世界的地位。 今天在Morgan Stanley的科技访谈会上,InfoWorld的编辑和Stroustrup畅聊了很多关于C++的问题,还谈及了其他的编程语言,包括Google的Go语言和苹果的Swift语言。以下是我们的访谈记录。 InfoWorld: 您是怎么看C++的未来的?现在有很多流行的脚本语言,像Python和Javascript,当然还有很受欢迎的Java,甚至是Google的Go语言,C++如何从这么多编程语言中存活下来,并且发展壮大? Stroustrup: 这是个很棒的问题。在这 20年时间里,人们一直在预测C++将会灭亡,但是很高兴的是它一直在成长和壮大。如果你进入到嵌入式领域,如果你想做一些复杂的图像处理,如果你需要实 现一些微电子应用,如果你要开发一些金融管理系统,那么C++是你的首选。也许你很少能看到C++的身影,但是在那些应用的底层,C++依然是撑起整个应 用的顶梁柱。比如Google、Amazon、搜索引擎等那些需要高性能的地方,C++就成了不可或缺的重要角色了。 InfoWorld: Google的Go语言越来越被受到关注,您对Go语言的前景怎么看? Stroustrup: 当然这些编程语言可以非常优雅地实现一些功能,但是这些编程语言关注的是如何让写代码变得便捷和优雅,却损失不少性能。当然,这些编程语言所做的贡献我们也是有目共睹的。 InfoWorld: 一些脚本语言的宗旨是解放程序员的双手,那么C++是否也会逐渐倾向于这个目标? Stroustrup: Oh,当然了。C++主 要是为一些相当底层核心的应用设计的,它也经常会和其他的脚本语言结合使用。一开始的时候,我是用C++来实现任何的应用,然后我就在Unix上使用 shell作为脚本语言设计一些底层应用。C++涵盖了以下优秀的特性:高性能、易伸缩、占用空间小、占用资源少等等。 InfoWorld: 苹果在今年6月份发布了Swift语言,您是否认为由于苹果公司的支持,Swift将越来越受到开发者的关注? Stroustrup: 我认为是的,之前他们关注Objective-C,这回Swift真正进入了这些开发者的领域了。 InfoWorld: C++面临两大挑战:一方面要满足开发者实现高性能、可扩展、搞可靠性的应用程序,另一方面又需要能够帮助开发者实现可维护的代码。关于这两个问题您怎么看? Stroustrup: 我正要解释这两个问题,第一个问题是要尽可能的抽象和更高效地利用硬件资源,而后者则需要能尽可能简化代码的编写过程,从C++ 11到C++ 14,已经具备这样的兼顾能力了。 今年我们会发布一个新的C++版本,它参考了C++ 14的标准。当你在研发大型的产品时,也许C++ 11在某些方面已经无法满足你的需求,但当出现C++ 14时,情况就会完全改变了,C++总是在不停地进步着。 InfoWorld: 关于程序的安全性问题,您怎么看?程序员是否需要关注所有的安全问题?C++是否比其他编程语言安全呢? Stroustrup: 我非常热衷于解决硬件的安全问题。在编程语言方面,如果你想编写优秀的程序,那么你的代码一定要确保类型安全。你可以在C++中实现这一要求。不要总是围绕着一些低效的功能转,总的来说,安全问题是系统问题。 InfoWorld: 您是否还要探讨关于C++或者软件开发的其他任何问题? Stroustrup: 我们的目标是让软件开发更加专业化。我们的社会中很多事情都是不能被打破的,其中大部分都需要依赖软件。作为开发者,我们需要整体考虑到我们的系统,编程语言和开发工具只是其中的一部分,我们需要探究如何培养开发者,以及如何将重点放在程序的可靠性上。 原文出处: infoworld 译文出处:codeceo from:http://www.oschina.net/news/54556/stroustrup-why-the-35-year-old-c-still-dominates-real-dev
View Details几周前我在不同的地方读到了有关C#6的一些新特性。我就决定把它们都收集到一起,如果你还没有读过,就可以一次性把它们都过一遍。它们中的一些可能不会如预期那样神奇,但那也只是目前的更新。 你可以通过下载VS2014或者安装这里针对visual studio2013的Roslyn包来获取它们。 那么让我们看看吧: 1. $标识符 $的作用是简化字符串索引。它与C#中那些内部使用正则表达式匹配实现索引的动态特性不同。示例如下: ? 1 2 3 4 5 6 7 8 9 10 11 var col = new Dictionary<string, string>() { $first = "Hassan" }; //Assign value to member //the old way: col.$first = "Hassan"; //the new way: col["first"] = "Hassan"; 2. 异常过滤器 VB编译器中早已支持异常过滤器,现在C#也支持了。异常过滤器可以让开发人员针对某一条件创建一个catch块。只有当条件满足时catch块中的代码才会执行,这是我最喜欢的特性之一,示例如下: ? 1 2 3 4 5 try { throw new Exception("Me"); } catch (Exception ex) if (ex.Message == "You") 3. catch和finally块中await关键字 据我所知,没有人知道C# 5中catch和finally代码块内await关键字不可用的原因,无论何种写法它都是不可用的。这点很好因为开发人员经常想查看I/O操作日志,为了将捕捉到的异常信息记录到日志中,此时需要异步进行。 ? 1 2 3 4 5 6 7 8 try { DoSomething(); } catch (Exception) { await LogService.LogAsync(ex); } 4. 声明表达式 这个特性允许开发人员在表达式中定义一个变量。这点很简单但很实用。过去我用asp.net做了许多的网站,下面是我常用的代码: ? 1 2 3 long id; if (!long.TryParse(Request.QureyString["Id"], out id)) { } 优化后的代码: ? 1 2 if (!long.TryParse(Request.QureyString["Id"], out long id)) { } 这种声明方式中变量的作用域和C#使用一般方式声明变量的作用域是一样的。 5. Static的使用 这一特性允许你在一个using语句中指定一个特定的类型,此后这个类型的所有静态成员都能在后面的子句中使用了. ? 1 2 […]
View Details增加、减少随机抽中几率——此算法可用于题库随机抽题、赌博机控制出彩率,甚至俄罗斯方块等游戏,有广泛的用途!也希望能帮得到你! 强调 在随机的基础上增控制抽中几率,注意随机性!! 正文 一、文字解说: 为待随机抽取的集合每个项加一个权值,这个权值就是随机几率,比如正常被抽正的几率为1,那么将希望被抽中几率更大的项的权值设置为3或5,然后随机抽取集合中的项,并将随机数乘以每个项对应的权值,然后排序!!提取前N个项即可!大家可以发现权值更高被乘之后有更高几率排在前面而被抽中,如果将权值设为0将永远也不会被抽中! 二、应用场景: 1. 随机抽题:如果题A去年考过了,那么我希望今年出现的几率更小或者不出现,那么我将题A的权值设置为0,这道题将在以后的考试随机抽题中永远不会被随机抽中;而另外题B是本院今年模拟考试中的一道题目,我将这道题权值增加到5,根据算法,那么这道题目在下次随机抽题抽中率将比普通题目提高数倍! 2. 赌博机:大家知道游戏厅里面的赌博机是可以调的,被人调了之后出彩率明显提高或者降低,我觉得本算法适合解释。假设赌博机有24个赌项可供选择,分别是A-Z各个字母,按正常几率的话每个项的权值都是1,调机师可以通过动态改变权值来达到提高或降低中奖率。假如你投三个币,分别选了A、B、C,赌博机根据调机师的设置动态改变了A、B、C的权值,让灯转3-4圈后更大的几率停留在这三个选择中奖金较少的一个。 3. 俄罗斯方块:大家在打QQ俄罗斯方块对打的时候,有时候明显感觉堆得越高,出的东西反而不顺意,我觉得本算法也可以达到这个效果。计算机能算得出下一个最优方案是出条还是出角最好,所以可以通过调整权值来打破平均出现的几率来达到这个目的! 三、代码实现(C#实现): RandomController.cs using System; using System.Collections.Generic; using System.Text; /* 为待随机抽取的集合每个项加一个权值,这个权值就是随机几率,比如正常被抽正的几率为1, 那么将希望被抽中几率更大的项的权值设置为3或5,然后随机抽取集合中的项,并将随机数 乘以每个项对应的权值,然后排序!!提取前N个项即可!大家可以发现权值更高被乘之后 有更高几率排在前面而被抽中,如果将权值设为0将永远也不会被抽中! */ namespace 随机抽奖 { public class RandomController { #region Properties private int _Count; /// <summary> /// 随机抽取个数 /// </summary> public int Count { get{return _Count;} set{_Count = value;} } #endregion #region Member Variables /// <summary> /// 待随机抽取数据集合 /// </summary> public List<char> datas = new List<char>( new char[]{ 'A',’B',’C',’D',’E',’F', 'G',’H',’I',’J',’K',’L', 'M',’N',’O',’P',’Q',’R', 'S',’T',’U',’V',’W',’X', 'Y',’Z' […]
View Details队列(Queue)在程序设计中扮演着重要的角色,因为它可以模拟队列的数据操作。例 如,排队买票就是一个队列操作,新来的人排在后面,先来的人排在前面,并且买票请求 先被处理。为了模拟队列的操作,Queue在ArrayList的基础上加入了以下限制: · 元素采用先入先出机制(FIFO,First In First Out),即先进入队列的元素必须先离 开队列。最先进入的元素称为队头元素。 · 元素只能被添加到队尾(称为入队),不允许在中间的某个位置插入。也就是说, 不支持ArrayList中的Insert方法。 · 只有队头的元素才能被删除(称为出队),不允许直接对队列中的非队头元素进行 删除,从而保证FIFO机制。也就是说,不支持ArrayList中的Remove方法。 · 不允许直接对队列中非队头元素进行访问。也就是说,不支持ArrayList中的索引访 问,只允许遍历访问。 下面的实例展示了如何创建Queue对象,并向Queue对象中入队数据、出队数据、遍历 数据。 创建TestQueue类,在TestQueue.cs中输入如下代码: using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace Chapter12 { class TestQueue { static void Print(Queue list) { Console.Write("队列内容:"); foreach (string str in list) System.Console.Write(str + " "); } static void Main(string[] args) { Queue list = new Queue(); //Add elements Console.WriteLine("输入字符串添加到队列(#号结束):"); string str; do { str = Console.ReadLine(); if (str == "#") break; else { list.Enqueue(str); } } while (true); TestQueue.Print(list); Console.WriteLine(); //Remove elements Console.WriteLine("出队字符串:"); while (list.Count != 0) […]
View Detailsvolatile 关键字指示一个字段可以由多个同时执行的线程修改。 声明为 volatile 的字段不受编译器优化(假定由单个线程访问)的限制。 这样可以确保该字段在任何时间呈现的都是最新的值。 volatile 修饰符通常用于由多个线程访问但不使用 lock 语句对访问进行序列化的字段。 volatile 关键字可应用于以下类型的字段: 引用类型。 指针类型(在不安全的上下文中)。 请注意,虽然指针本身可以是可变的,但是它指向的对象不能是可变的。 换句话说,您无法声明“指向可变对象的指针”。 类型,如 sbyte、byte、short、ushort、int、uint、char、float 和 bool。 具有以下基类型之一的枚举类型:byte、sbyte、short、ushort、int 或 uint。 已知为引用类型的泛型类型参数。 IntPtr 和 UIntPtr。 可变关键字仅可应用于类或结构字段。 不能将局部变量声明为 volatile。 示例 下面的示例说明如何将公共字段变量声明为 volatile。 C#
1 2 3 4 5 6 7 8 9 |
<span style="color: blue;">class</span> VolatileTest { <span style="color: blue;">public</span> <span style="color: blue;">volatile</span> <span style="color: blue;">int</span> i; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Test(<span style="color: blue;">int</span> _i) { i = _i; } } |
下面的示例演示如何创建辅助线程,并用它与主线程并行执行处理。 有关多线程处理的背景信息,请参见托管线程处理和线程处理(C# 和 Visual Basic)。 C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<span style="color: blue;">using</span> System; <span style="color: blue;">using</span> System.Threading; <span style="color: blue;">public</span> <span style="color: blue;">class</span> Worker { <span style="color: green;">// This method is called when the thread is started.</span> <span style="color: blue;">public</span> <span style="color: blue;">void</span> DoWork() { <span style="color: blue;">while</span> (!_shouldStop) { Console.WriteLine(<span style="color: #a31515;">"Worker thread: working..."</span>); } Console.WriteLine(<span style="color: #a31515;">"Worker thread: terminating gracefully."</span>); } <span style="color: blue;">public</span> <span style="color: blue;">void</span> RequestStop() { _shouldStop = <span style="color: blue;">true</span>; } <span style="color: green;">// Keyword volatile is used as a hint to the compiler that this data</span> <span style="color: green;">// member is accessed by multiple threads.</span> <span style="color: blue;">private</span> <span style="color: blue;">volatile</span> <span style="color: blue;">bool</span> _shouldStop; } <span style="color: blue;">public</span> <span style="color: blue;">class</span> WorkerThreadExample { <span style="color: blue;">static</span> <span style="color: blue;">void</span> Main() { <span style="color: green;">// Create the worker thread object. This does not start the thread.</span> Worker workerObject = <span style="color: blue;">new</span> Worker(); Thread workerThread = <span style="color: blue;">new</span> Thread(workerObject.DoWork); <span style="color: green;">// Start the worker thread.</span> workerThread.Start(); Console.WriteLine(<span style="color: #a31515;">"Main thread: starting worker thread..."</span>); <span style="color: green;">// Loop until the worker thread activates.</span> <span style="color: blue;">while</span> (!workerThread.IsAlive) ; <span style="color: green;">// Put the main thread to sleep for 1 millisecond to</span> <span style="color: green;">// allow the worker thread to do some work.</span> Thread.Sleep(1); <span style="color: green;">// Request that the worker thread stop itself.</span> workerObject.RequestStop(); <span style="color: green;">// Use the Thread.Join method to block the current thread </span> <span style="color: green;">// until the object's thread terminates.</span> workerThread.Join(); Console.WriteLine(<span style="color: #a31515;">"Main thread: worker thread has terminated."</span>); } <span style="color: green;">// Sample output:</span> <span style="color: green;">// Main thread: starting worker thread...</span> <span style="color: green;">// Worker thread: working...</span> <span style="color: green;">// Worker thread: working...</span> <span style="color: green;">// Worker thread: working...</span> <span style="color: green;">// Worker thread: working...</span> <span style="color: green;">// Worker thread: working...</span> <span style="color: green;">// Worker thread: working...</span> <span style="color: green;">// Worker thread: terminating gracefully.</span> <span style="color: green;">// Main thread: worker thread has terminated.</span> } from:http://msdn.microsoft.com/zh-cn/library/x13ttww7.aspx |