服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#使用读写锁三行代码简单解决多线程并发的问题

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

2021-12-14 13:56弎吩锺熱℃ C#

本文主要介绍了C#使用读写锁三行代码简单解决多线程并发写入文件时提示“文件正在由另一进程使用,因此该进程无法访问此文件”的问题。需要的朋友可以参考借鉴

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

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

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

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

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

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

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

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

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

don't talk, show me the code.

1.多线程同时写入文件

?
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
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);
 }
 }
 }

运行结果:

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

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

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

?
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
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();
 }
 }
 }

运行结果:

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

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

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

?
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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();
}
}
}

运行结果:

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
65
66
67
...
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://www.cnblogs.com/Tench/p/6159763.html

延伸 · 阅读

精彩推荐
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15