Bonjour,
Je désire me faire une classe de Logging thread-safe. Malgré plusieurs essais, il arrive toujours un moment ou j'obtiens des exceptions :
Pourriez-vous m'aider à trouver ce que je fais de mal ?
Code : Sélectionner tout - Visualiser dans une fenêtre à part The process cannot access the file 'Application.log' because it is being used by another process.
Voici ma classe :
J'appelle ma classe de Logging de la façon suivante :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 Imports System.IO Imports System.Threading Public Class Logging ' Signleton Private Shared instance As Logging = Nothing Private Shared ReadOnly myLock As New Object() Private m_lock As New System.Threading.ReaderWriterLock Private Sub New() End Sub Public Shared Function GetInstance() As Logging SyncLock (myLock) If instance Is Nothing Then instance = New Logging() End If Return instance End SyncLock End Function ' End Signleton Private m_fileName As String Public Property FileName As String Get Return m_fileName End Get Set(ByVal value As String) m_fileName = value End Set End Property Private m_sw As StreamWriter = Nothing Private m_currDate As Date = DateTime.Now() Public Sub Add(ByVal str As String) Try m_lock.AcquireWriterLock(100) Try If DateTime.Now().Day <> m_currDate.Day Then Dim newfile As New FileInfo(m_fileName) If newfile.Exists Then m_sw = New StreamWriter(m_fileName, True) m_sw.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " - Day is over, renaming file and creating new one ...") m_sw.Close() m_sw = Nothing newfile.MoveTo(m_fileName + "." + m_currDate.ToString("ddMMyyyy") + ".log") m_currDate = DateTime.Now() End If End If m_sw = New StreamWriter(m_fileName, True) m_sw.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " - " + str) m_sw.Close() m_sw = Nothing Finally m_lock.ReleaseWriterLock() End Try Catch ex As ApplicationException Catch e As IOException EventLog.WriteEntry("MyServer", "Could not operate log file actions : " + e.Message) 'm_sw = New StreamWriter(m_fileName, True) 'm_sw.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " - Error in adding line to log file " + e.Message) 'm_sw.Close() 'm_sw = Nothing End Try End Sub End Class
Je précise, au début j'avais créé ma classe sans objet ReaderWriterLock, je l'ai rajouté entre-temps suite à mes recherches sur internet, mais malgré cela je continue à avoir des exceptions.
Code : Sélectionner tout - Visualiser dans une fenêtre à part Logging.GetInstance().Add("ChangeChannel has been called for " + Sender + " on channel " + Channel)
Un idée ?
D'avance je vous en remercie,
Dominique
Partager