好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用读写锁三行代码简单解决多线程并发的问题

在开发程序的过程中,难免少不了写入错误日志这个关键功能。实现这个功能,可以选择使用第三方日志插件,也可以选择使用数据库,还可以自己写个简单的方法把错误信息记录到日志文件。

选择最后一种方法实现的时候,若对文件操作与线程同步不熟悉,问题就有可能出现了,因为同一个文件并不允许多个线程同时写入,否则会提示[ 文件正在由另一进程使用,因此该进程无法访问此文件 ]。

这是文件的并发写入问题,就需要用到线程同步。而微软也给线程同步提供了一些相关的类可以达到这样的目的,本文使用到的 system.threading.readerwriterlockslim 便是其中之一。

该类用于管理资源访问的锁定状态,可实现多线程读取或进行独占式写入访问。利用这个类,我们就可以避免在同一时间段内多线程同时写入一个文件而导致的并发写入问题。

读写锁是以 readerwriterlockslim 对象作为锁管理资源的, 不同的 readerwriterlockslim 对象中锁定同一个文件也会被视为不同的锁进行管理,这种差异可能会再次导致文件的并发写入问题,所以 readerwriterlockslim 应尽量定义为只读的静态对象。

readerwriterlockslim 有几个关键的方法,本文仅讨论写入锁:

调用 enterwritelock 方法 进入写入状态,在调用线程 进入锁定状态之前一直处于阻塞状态 ,因此 可能永远都不返回 。

调用 tryenterwritelock 方法 进入写入状态,可指定阻塞的间隔时间,如果调用线程在此 间隔期间并未进入写入模式,将返回false。

调用 exitwritelock 方法 退出写入状态, 应使用 finally 块执行 exitwritelock 方法,从而确保调用方退出写入模式。

don't talk, show me the code.

1.多线程同时写入文件

?

class program

  {

  static int logcount = 100;

  static int writedcount = 0;

  static int failedcount = 0;

  static void main( string [] args)

  {

  //迭代运行写入日志记录,由于多个线程同时写入同一个文件将会导致错误

  parallel. for (0, logcount, e =>

  {

  writelog();

  });

  console.writeline( string .format( "\r\nlog count:{0}.\t\twrited count:{1}.\tfailed count:{2}." , logcount.tostring(), writedcount.tostring(), failedcount.tostring()));

  console.read();

  }

  static void writelog()

  {

  try

  {

  var logfilepath = "log.txt" ;

  var now = datetime.now;

  var logcontent = string .format( "tid: {0}{1} {2}.{3}\r\n" , thread.currentthread.managedthreadid.tostring().padright(4), now.tolongdatestring(), now.tolongtimestring(), now.millisecond.tostring());

  file.appendalltext(logfilepath, logcontent);

  writedcount++;

  }

  catch (exception ex)

  {

  failedcount++;

  console.writeline(ex.message);

  }

  }

  }

运行结果:

不使用读写锁,只有部分日志成功写入了日志文件。

2.多线程使用读写锁同步写入文件

?

class program

  {

  static int logcount = 100;

  static int writedcount = 0;

  static int failedcount = 0;

  static void main( string [] args)

  {

  //迭代运行写入日志记录

  parallel. for (0, logcount, e =>

  {

  writelog();

  });

  console.writeline( string .format( "\r\nlog count:{0}.\t\twrited count:{1}.\tfailed count:{2}." , logcount.tostring(), writedcount.tostring(), failedcount.tostring()));

  console.read();

  }

  //读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入

  static readerwriterlockslim logwritelock = new readerwriterlockslim();

  static void writelog()

  {

  try

  {

  //设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入

  //注意:长时间持有读线程锁或写线程锁会使其他线程发生饥饿 (starve)。 为了得到最好的性能,需要考虑重新构造应用程序以将写访问的持续时间减少到最小。

  // 从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度

  // 因进入与退出写入模式应在同一个try finally语句块内,所以在请求进入写入模式之前不能触发异常,否则释放次数大于请求次数将会触发异常

  logwritelock.enterwritelock();

  var logfilepath = "log.txt" ;

  var now = datetime.now;

  var logcontent = string .format( "tid: {0}{1} {2}.{3}\r\n" , thread.currentthread.managedthreadid.tostring().padright(4), now.tolongdatestring(), now.tolongtimestring(), now.millisecond.tostring());

 

  file.appendalltext(logfilepath, logcontent);

  writedcount++;

  }

  catch (exception)

  {

  failedcount++;

  }

  finally

  {

  //退出写入模式,释放资源占用

  //注意:一次请求对应一次释放

  // 若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]

  // 若请求处理完成后未释放将会触发异常[此模式不下允许以递归方式获取写入锁定]

  logwritelock.exitwritelock();

  }

  }

  }

运行结果:

使用读写锁,全部日志成功写入了日志文件。

3.测试复杂多线程环境下使用读写锁同步写入文件

?

class program

{

static int logcount = 1000;

static int sumlogcount = 0;

static int writedcount = 0;

static int failedcount = 0;

static void main( string [] args)

{

//往线程池里添加一个任务,迭代写入n个日志

sumlogcount += logcount;

threadpool.queueuserworkitem((obj) =>

{

parallel. for (0, logcount, e =>

{

writelog();

});

});

//在新的线程里,添加n个写入日志的任务到线程池

sumlogcount += logcount;

var thread1 = new thread(() =>

{

parallel. for (0, logcount, e =>

{

threadpool.queueuserworkitem((subobj) =>

{

writelog();

});

});

});

thread1.isbackground = false ;

thread1.start();

//添加n个写入日志的任务到线程池

sumlogcount += logcount;

parallel. for (0, logcount, e =>

{

threadpool.queueuserworkitem((obj) =>

{

writelog();

});

});

//在新的线程里,迭代写入n个日志

sumlogcount += logcount;

var thread2 = new thread(() =>

{

parallel. for (0, logcount, e =>

{

writelog();

});

});

thread2.isbackground = false ;

thread2.start();

//在当前线程里,迭代写入n个日志

sumlogcount += logcount;

parallel. for (0, logcount, e =>

{

writelog();

});

console.writeline( "main thread processed.\r\n" );

while ( true )

{

console.writeline( string .format( "sum log count:{0}.\t\twrited count:{1}.\tfailed count:{2}." , sumlogcount.tostring(), writedcount.tostring(), failedcount.tostring()));

console.readline();

}

}

//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入

static readerwriterlockslim logwritelock = new readerwriterlockslim();

static void writelog()

{

try

{

//设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入

//注意:长时间持有读线程锁或写线程锁会使其他线程发生饥饿 (starve)。 为了得到最好的性能,需要考虑重新构造应用程序以将写访问的持续时间减少到最小。

// 从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度

// 因进入与退出写入模式应在同一个try finally语句块内,所以在请求进入写入模式之前不能触发异常,否则释放次数大于请求次数将会触发异常

logwritelock.enterwritelock();

var logfilepath = "log.txt" ;

var now = datetime.now;

var logcontent = string .format( "tid: {0}{1} {2}.{3}\r\n" , thread.currentthread.managedthreadid.tostring().padright(4), now.tolongdatestring(), now.tolongtimestring(), now.millisecond.tostring());

file.appendalltext(logfilepath, logcontent);

writedcount++;

}

catch (exception)

{

failedcount++;

}

finally

{

//退出写入模式,释放资源占用

//注意:一次请求对应一次释放

// 若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]

// 若请求处理完成后未释放将会触发异常[此模式不下允许以递归方式获取写入锁定]

logwritelock.exitwritelock();

}

}

}

运行结果:

部分日志文件内容:

?

...

tid: 36 2016年12月11日 15:29:22.825

tid: 29 2016年12月11日 15:29:22.830

tid: 6 2016年12月11日 15:29:22.838

tid: 26 2016年12月11日 15:29:22.845

tid: 34 2016年12月11日 15:29:22.854

tid: 24 2016年12月11日 15:29:22.863

tid: 27 2016年12月11日 15:29:22.872

tid: 14 2016年12月11日 15:29:22.877

tid: 23 2016年12月11日 15:29:22.886

tid: 20 2016年12月11日 15:29:22.892

tid: 30 2016年12月11日 15:29:22.898

tid: 9 2016年12月11日 15:29:22.904

tid: 21 2016年12月11日 15:29:22.909

tid: 22 2016年12月11日 15:29:22.915

tid: 7 2016年12月11日 15:29:22.920

tid: 3 2016年12月11日 15:29:22.925

tid: 12 2016年12月11日 15:29:22.931

tid: 5 2016年12月11日 15:29:22.937

tid: 13 2016年12月11日 15:29:22.942

tid: 11 2016年12月11日 15:29:22.947

tid: 19 2016年12月11日 15:29:22.953

tid: 37 2016年12月11日 15:29:22.958

tid: 37 2016年12月11日 15:29:22.964

tid: 40 2016年12月11日 15:29:22.970

tid: 40 2016年12月11日 15:29:22.975

tid: 40 2016年12月11日 15:29:22.980

tid: 40 2016年12月11日 15:29:22.985

tid: 40 2016年12月11日 15:29:22.991

tid: 40 2016年12月11日 15:29:22.997

tid: 31 2016年12月11日 15:29:23.3

tid: 31 2016年12月11日 15:29:23.9

tid: 31 2016年12月11日 15:29:23.14

tid: 31 2016年12月11日 15:29:23.20

tid: 31 2016年12月11日 15:29:23.27

tid: 31 2016年12月11日 15:29:23.33

tid: 31 2016年12月11日 15:29:23.38

tid: 31 2016年12月11日 15:29:23.44

tid: 31 2016年12月11日 15:29:23.49

tid: 31 2016年12月11日 15:29:23.57

tid: 31 2016年12月11日 15:29:23.63

tid: 31 2016年12月11日 15:29:23.68

tid: 31 2016年12月11日 15:29:23.74

tid: 16 2016年12月11日 15:29:23.80

tid: 16 2016年12月11日 15:29:23.86

tid: 16 2016年12月11日 15:29:23.93

tid: 16 2016年12月11日 15:29:23.99

tid: 16 2016年12月11日 15:29:23.105

tid: 16 2016年12月11日 15:29:23.110

tid: 16 2016年12月11日 15:29:23.116

tid: 38 2016年12月11日 15:29:23.122

tid: 38 2016年12月11日 15:29:23.128

tid: 28 2016年12月11日 15:29:23.134

tid: 19 2016年12月11日 15:29:23.139

tid: 25 2016年12月11日 15:29:23.146

tid: 37 2016年12月11日 15:29:23.152

tid: 39 2016年12月11日 15:29:23.158

tid: 32 2016年12月11日 15:29:23.164

tid: 33 2016年12月11日 15:29:23.170

tid: 31 2016年12月11日 15:29:23.176

tid: 35 2016年12月11日 15:29:23.182

tid: 40 2016年12月11日 15:29:23.189

tid: 15 2016年12月11日 15:29:23.194

tid: 18 2016年12月11日 15:29:23.202

tid: 17 2016年12月11日 15:29:23.208

tid: 10 2016年12月11日 15:29:23.215

tid: 16 2016年12月11日 15:29:23.221

复杂多线程环境下使用读写锁,全部日志成功写入了日志文件,由threadid和datetime可以看出是由不同的线程同步写入。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://HdhCmsTestcnblogs测试数据/Tench/p/6159763.html

dy("nrwz");

查看更多关于C#使用读写锁三行代码简单解决多线程并发的问题的详细内容...

  阅读:45次