当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET:一段比较经典的多线程学习代码

ASP.NET
利用Timer在ASP.NET中实现计划任务的方法
asp.net下出现其中的组件“访问被拒绝”的解决方法
学习使用ASP.NET 2.0的本地化
asp.net 1.1/ 2.0 中快速实现单点登陆
ASP.NET用户控件技术
asp.net 2.0 中的URL重写以及urlMappings问题
asp.net 的错误处理机制讲解
asp.net下cookies的丢失和中文乱码
用WebClient.UploadData方法上载文件数据的方法
用程序修改IIS目录的Asp.Net版本
ASP.NET中常用的优化性能的方法
asp.net下URL处理两个小工具方法
asp.net下DataSet.WriteXml(String)与(Stream)的区别
asp.net下用DataSet生成XML的问题
从别人那拷下来的几点Session使用的经验
ASP.net在页面所有内容生成后、输出内容前对页面内容进行操作
asp.net(c#)Enterprise Library 3.0 下载
近几天对DataSet的新认识
.net下实现Word动态填加数据打印
ASP.NET 链接 Access 数据库路径问题最终解决方案

ASP.NET:一段比较经典的多线程学习代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 96 ::
收藏到网摘: n/a

  一段比较经典的多线程学习代码。

  1、用到了多线程的同步问题。
  2、用到了多线程的顺序问题。

  如果有兴趣的请仔细阅读下面的代码。注意其中代码段的顺序,思考一下,这些代码的顺序能否互相调换,为什么?这应该对学习很有帮助的。为了演示,让所有的线程都Sleep了一段时间。

using System.Net;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Webb.Study
{
class TestThread
{
static Mutex m_Mutex = new Mutex();
static Thread[] m_testThreads = new Thread[10];
static int m_threadIndex = 0;

static void ThreadCallBack()
{
TestThread.m_Mutex.WaitOne();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex();
Console.WriteLine("Thread {0} start.",m_index);
for(int i=0;i<=10;i++)
{
TestThread.m_Mutex.WaitOne();
Console.WriteLine("Thread {0}: is running. {1}",m_index,i);
TestThread.m_Mutex.ReleaseMutex();
Thread.Sleep(100);
}
Console.WriteLine("Thread {0} end.",m_index);
}

public static void Main(String[] args)
{
Console.WriteLine("Main thread start.");
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_threadIndex = i;
TestThread.m_testThreads[i] = new Thread(new ThreadStart(ThreadCallBack));
TestThread.m_testThreads[i].Start();
Thread.Sleep(100);
}
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_testThreads[i].Join();
}
Console.WriteLine("Main thread exit.");
}
}
}

  1、主函数中这两句能否互换?为什么?

TestThread.m_testThreads[i].Start();
Thread.Sleep(100);

  2、CallBack函数中这两句能否互换?为什么?会有什么不同的结果?

TestThread.m_Mutex.ReleaseMutex();
Thread.Sleep(100);

  3、主函数能否写成这样?为什么?会有什么不同的结果?

public static void Main(String[] args)
{
Console.WriteLine("Main thread start.");
for(int i=0;i<TestThread.m_testThreads.Length;i++)
{
TestThread.m_threadIndex = i;
TestThread.m_testThreads[i] = new Thread(new ThreadStart(ThreadCallBack));
TestThread.m_testThreads[i].Start();
TestThread.m_testThreads[i].Join();
Thread.Sleep(100);
}
Console.WriteLine("Main thread exit.");
}

  4、这几句的作用是什么?那么程序中还存在什么样的问题?应该做怎样的修改?

TestThread.m_Mutex.WaitOne();
int m_index = m_threadIndex;
TestThread.m_Mutex.ReleaseMutex();

仅做学习讨论。