代码的作用在于保证在上端缓存服务失效(一般来说概率比较低)时,形成倒瓶颈,从而能够保护数据库,数据库宕了,才是大问题(比如影响其他应用)。
假设(非完全正确数据,仅做示例):
每秒支持10,000,000次查询(千万);
一次读库需要耗时:1ms;
修改内存变量需要耗时:0.001ms;
那么:
每秒最终访问的数据库的请求数量 < 1000
其他的9,900,000个请求会返回到其他页面。这就是为啥很多抢单网站有人可以访问,而有人得到繁忙中页面的原因。
微观到1ms来看,在currentvalidsessionid == -1的时间是 1ms,从而平均会有10000条记录涌入。
currentvalidsessionid从-1变为其他值的时间为0.001ms,这个时间内,
lock (databasedoor)
{
// now there is only one request can reach below codes.
if (currentvalidsessionid == -1)
{
currentvalidsessionid = currentrequest.sessionid;
}
}
平均会有 10000×0.001=10条记录会执行到上述这段代码,操作系统会为锁形成等待序列。
那么我们的目标是,每毫秒只允许一次读库(因为其他应用也会使用),所以我们只希望这进入的10条,最终只有一条能够继续前进。
那么这就是
if (currentvalidsessionid == -1)
{
}
的作用了。再次进行一次判断,进入原子保护队列的请求,也只有一个能够继续。
一点思考:
其实对于一个主频能上n ghz的服务器来说,一个内存数赋值给另一个内存数据就是1~4条指令(平均2条,两次mov操作),也就是2/n ns时间,而不是我们上述假设的 1000ns(0.001ms)。其实不用原子,我们已经可以把千亿级请求的访问数控制在个位数。
不过一个架构师,如果可以用一个99.99%安全的方案,就绝对不用99.9%。 so。
public static long currentvalidsessionid = -1;
public static object databasedoor = new object();
void readdatabase(request currentrequest)
{
// use currentvalidsessionid to filter out other requests came in during the execute time gap
if (currentvalidsessionid == -1)
{
// use object-lock to filter out other requests came in during the variable change time gap.
lock (databasedoor)
{
// now there is only very little number of requests can reach below codes.
if (currentvalidsessionid == -1)
{ // now there will be only one request can access the database
currentvalidsessionid = currentrequest.sessionid;
}
}
}
if (currentvalidsessionid == currentrequest.sessionid)
{ // here is the one !
try
{
// use transaction to guarantee the execute time to void block
// access database codes go here
}
catch()
{
// exception codes go here
}
finally
{
currentvalidsessionid = -1; // recover to original state
}
}
}
以上就是本文所述的全部内容了,希望对大家学习c#的高并发编程能够有所帮助。
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
深入了解c# 匿名类型
一、什么叫做匿名类? 匿名类就是没有名字的类。匿名类不能被引用,只能再创建的时候用new语句来声明。二、匿名类的优势以及应用场景; 1、匿名类型提供了一种方...
[阅读全文]
-
-
C# 实现俄罗斯方块(附源码)
概述俄罗斯方块(tetris)是一款由俄罗斯人阿列克谢·帕基特诺夫发明的休闲游戏,帕基特诺夫爱玩拼图,从拼图游戏里得到灵感,设计出了俄罗斯方块。由于上手简单、老...
[阅读全文]
-
浅析c# 接口
接口:是指定一组函数成员而不是实现他们的引用类型。所以只能类喝啊结构来实现接口,在结成该接口的类里面必须要实现接口的所有方法接口的特点:继承于接口的类,必须要实...
[阅读全文]
-
c# 接口使用实例
用接口实现一个简单的物件的入库,出库如定义一个物流类接口,包含物件所属快递公司名称属性,物件单号属性及信息显示方法。通过物件出库类信息和物件入库类信息继承该接口...
[阅读全文]
-
-
-
-
-
网友评论