使用httpHandle来实现,对图片文件的请求做专门的处理 第一步:创建一个类,继承自IHttpHandler,代码如下 C# code using System; using System.Web; namespace CustomHandler{ public class JpgHandler : IHttpHandler{ public void ProcessRequest(HttpContext context){ // 获取文件服务器端物理路径 string FileName = context.Server.MapPath(context.Request.FilePath); // 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片 if (context.Request.UrlReferrer.Host == null){ context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/error.jpg"); }else{ // 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片 if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){ context.Response.ContentType = "image/JPEG"; context.Response.WriteFile(FileName); }else{ context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/error.jpg"); } } } public bool IsReusable{ get{ return true; } } } } 第二步:编译成DLL csc /t:library CustomHandler.cs 第三步:添加编译好的DLL引用到当前站点的bin文件夹下 第四步:在Web.Config 中注册这个Handler C# code <system.web> <httpHandlers> <add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="CustomHandler.JpgHandler,CustomHandler" /> </httpHandlers> </system.web> //verb指的是请求此文件的方式,可以是post或get,用*代表所有访问方式。CustomHandler.JpgHandler表示命名空间和类名,CustomHandler表示程序集名。 from:http://www.cnblogs.com/ghfsusan/archive/2011/02/25/1964579.html
View Details利用Global.asax的Application_BeginRequest 实现url 重写 无后缀 <%@ Application Language="C#" %> <script RunAt="server"> void Application_BeginRequest(object sender, EventArgs e) { string oldUrl = System.Web.HttpContext.Current.Request.RawUrl; //获取初始url //~/123.aspx → ~/Index.aspx?id=123 Regex reg = new Regex(@"^\/\d+\.html"); if (reg.IsMatch(oldUrl)) { string id = reg.Match(oldUrl).ToString().Substring(1, reg.Match(oldUrl).ToString().LastIndexOf(".") – 1); Context.RewritePath("~/Index.aspx?id=" + id); } //~/123 → ~/Index.aspx?id=123 Regex reg1 = new Regex(@"^\/\d+$"); if (reg1.IsMatch(oldUrl)) { string id = reg1.Match(oldUrl).ToString().Substring(1); Context.RewritePath("~/Index.aspx?id=" + id); } //~/index/123 → ~/Index.aspx?id=123 Regex reg3 = new Regex(@"^\/index\/\d+$"); if (reg3.IsMatch(oldUrl)) { string id = reg3.Match(oldUrl).ToString().Substring(7); Context.RewritePath("~/Index.aspx?id=" + id); } } </script> from:http://www.jb51.net/article/40587.htm
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环境说明: 操作系统:使用windows 2003 server 32位系统,IIS6。 PHP版本:官方下载PHP 5.3.26 VC9 x86 Non Thread SafeZIP版本。 IIS6 FastCGI安装包:FastCGI for IIS x86版本。 PHP路径:C:\php-5.3.26\ FastCGI相关文件和路径 : C:\WINDOWS\system32\inetsrv\fcgiext.dll C:\WINDOWS\system32\inetsrv\fcgiext.ini 配置步骤: 解压PHP文件,修改目录名放到C盘。目录地址为C:\php-5.3.26\ 复制php.ini-production改名为php.ini,先参考PHP.ini参数说明修改。 并修改PHP对FastCGI支持: 安装下载的FastCGI for IIS工具,本文下载的文件名为fcgisetup_1.5_rtw_x86.msi。安装完成后无提示,直接打开文件C:\WINDOWS\system32\inetsrv\fcgiext.ini在最后[Types]后添加以下
1 2 3 4 5 6 7 8 9 |
[Types] php=PHP [PHP] ExePath=C:\php-5.3.26\php-cgi.exe InstanceMaxRequests=10000 ActivityTimeout=600 RequestTimeout=600 EnvironmentVars=PHP_FCGI_MAX_REQUESTS:10000,PHPRC:C:\php-5.3.26\ |
检查IIS是否配置正确了FastCGI的调用。如下图: from:http://www.magicwinmail.com/setupiis/iis6fastcgi.html
View Details定义和用法 array_slice() 函数在数组中根据条件取出一段值,并返回。 注释:如果数组有字符串键,所返回的数组将保留键名。(参见例子 4) 语法
1 |
array_slice(<i>array</i>,<i>offset</i>,<i>length</i>,<i>preserve</i>) |
参数 描述 array 必需。规定输入的数组。 offset 必需。数值。规定取出元素的开始位置。 如果是正数,则从前往后开始取,如果是负值,从后向前取 offset 绝对值。 length 可选。数值。规定被返回数组的长度。 如果 length 为正,则返回该数量的元素。 如果 length 为负,则序列将终止在距离数组末端这么远的地方。 如果省略,则序列将从 offset 开始直到 array 的末端。 preserve 可选。可能的值: true – 保留键 false – 默认 – 重置键 例子 1
1 2 3 4 |
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2)); ?> |
输出:
1 |
Array ( [0] => Cat [1] => Horse ) |
例子 2 带有负的 offset 参数:
1 2 3 4 |
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,-2,1)); ?> |
输出:
1 |
Array ( [0] => Horse ) |
例子 3 preserve 参数设置为 true:
1 2 3 4 |
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2,true)); ?> |
输出:
1 |
Array ( [1] => Cat [2] => Horse ) |
例子 4 带有字符串键:
1 2 3 4 |
<?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","d"=>"Bird"); print_r(array_slice($a,1,2)); ?> |
输出:
1 |
Array ( [b] => Cat [c] => Horse ) |
队列(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 |
1. 源码下载: 下载地址:http://files.cnblogs.com/tianzhiliang/ManualResetEventDemo.rar Demo: 2. ManualResetEvent详解 ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 Reset 以将 ManualResetEvent 置于非终止状态,此线程可被视为控制 ManualResetEvent。调用 ManualResetEvent 上的 WaitOne 的线程将阻止,并等待信号。当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。一旦它被终止,ManualResetEvent 将保持终止状态(即对 WaitOne 的调用的线程将立即返回,并不阻塞),直到它被手动重置。可以通过将布尔值传递给构造函数来控制 ManualResetEvent 的初始状态,如果初始状态处于终止状态,为 true;否则为 false。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ManualResetEventDemo { class MREDemo { private ManualResetEvent _mre; public MREDemo() { this._mre = new ManualResetEvent(true); } public void CreateThreads() { Thread t1 = new Thread(new ThreadStart(Run)); t1.Start(); Thread t2 = new Thread(new ThreadStart(Run)); t2.Start(); } public void Set() { this._mre.Set(); } public void Reset() { this._mre.Reset(); } private void Run() { string strThreadID = string.Empty; try { while (true) { // 阻塞当前线程 this._mre.WaitOne(); strThreadID = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine("Thread(" + strThreadID + ") is running…"); Thread.Sleep(5000); } […]
View Details相关概念: 线程池可以看做容纳线程的容器; 一个应用程序最多只能有一个线程池; ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程; 线程池的作用: 线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。 如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止。 什么时候使用ThreadPool? ThreadPool 示例一 : ThreadPool_1.cs using System; using System.Text; using System.Threading; namespace 多线程 { public class Example { public static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc)); Console.WriteLine("Main thread does some work, then sleeps."); Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } static void ThreadProc(Object stateInfo) { // No state object was passed to QueueUserWorkItem, // so stateInfo is null. Console.WriteLine("Hello from the thread pool."); } } } ThreadPool 示例二 : ThreadPool_2.cs using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace CS_Test { class ThreadPool_Demo { // 用于保存每个线程的计算结果 static int[] result = new int[10]; //注意:由于WaitCallback委托的声明带有参数, // 所以将被调用的Fun方法必须带有参数,即:Fun(object obj)。 static void Fun(object obj) { int n = (int)obj; //计算阶乘 int fac = 1; for (int i = 1; i <= n; i++) { fac *= i; } //保存结果 result[n] = fac; } static void Main(string[] args) { //向线程池中排入9个工作线程 for (int i = 1; i <= 9 ; i++) { //QueueUserWorkItem()方法:将工作任务排入线程池。 ThreadPool.QueueUserWorkItem(new WaitCallback(Fun),i); // Fun 表示要执行的方法(与WaitCallback委托的声明必须一致)。 // i 为传递给Fun方法的参数(obj将接受)。 } //输出计算结果 for (int i = 1; i <= 9; i++) { Console.WriteLine("线程{0}: {0}! = {1}",i,result[i]); } } } } ThreadPool的作用: 参考来源: C#多线程学习(四) 多线程的自动管理(线程池) [叩响C#之门]写给初学者:多线程系列( 十一)——线程池(ThreadPool) from:http://www.cnblogs.com/xugang/archive/2010/04/20/1716042.html
View Details//封装类 [csharp] view plaincopyprint? using System; using System.Collections.Generic; using System.Linq; using System.Web; using Lucene.Net.Analysis; using Lucene.Net.Index; using Lucene.Net.Documents; using System.Reflection; using Lucene.Net.QueryParsers; using Lucene.Net.Search; namespace SearchTest { /// <summary> /// 盘古分词在lucene.net中的使用帮助类 /// 调用PanGuLuceneHelper.instance /// </summary> public class PanGuLuceneHelper { private PanGuLuceneHelper() { } #region 单一实例 private static PanGuLuceneHelper _instance = null; /// <summary> /// 单一实例 /// </summary> public static PanGuLuceneHelper instance { get { if (_instance == null) _instance = new PanGuLuceneHelper(); return _instance; } } #endregion #region 分词测试 /// <summary> /// 分词测试 /// </summary> /// <param name="keyword"></param> /// <returns></returns> public string Token(string keyword) { string ret = ""; System.IO.StringReader reader = new System.IO.StringReader(keyword); Lucene.Net.Analysis.TokenStream ts = analyzer.TokenStream(keyword, reader); bool hasNext = ts.IncrementToken(); Lucene.Net.Analysis.Tokenattributes.ITermAttribute ita; while (hasNext) { ita = ts.GetAttribute<Lucene.Net.Analysis.Tokenattributes.ITermAttribute>(); ret += ita.Term + "|"; hasNext = ts.IncrementToken(); } ts.CloneAttributes(); reader.Close(); analyzer.Close(); return ret; } #endregion #region 创建索引 /// <summary> /// 创建索引 /// </summary> /// <param name="datalist"></param> /// <returns></returns> public bool CreateIndex(List<MySearchUnit> datalist) { IndexWriter writer = null; try { writer = new IndexWriter(directory_luce, analyzer, false, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示删除之前的重新写入) } catch { writer = new IndexWriter(directory_luce, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示删除之前的重新写入) } foreach (MySearchUnit data in datalist) { CreateIndex(writer, data); } writer.Optimize(); […]
View Details