vb.net 写入文件同步锁

时间:2022-11-21 17:14:41
  <SoapHeader("oHeader")> _
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function Test_SyncLock() As String
Dim threads() As Threading.Thread
For i As Integer = To
threads(i) = New Threading.Thread(AddressOf PrintNumbers)
threads(i).Name = String.Format("Worker thread #{0}", i)
Next
' Now start each one.
For Each t As Threading.Thread In threads
t.Start()
Next
Return ""
End Function Private Sub PrintNumbers()
writeLog("", "a", Threading.Thread.CurrentThread.Name)
End Sub #Region "Write Log File" Private threadLock As Object = New Object()
Public Sub writeLog(ByVal dir As String, ByVal fileName As String, ByVal log As String) Dim filePath As String = System.IO.Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/"),
"Log/" & dir & "/" & fileName & ".log")
SyncLock threadLock
'创建目录
Dim dirPath As String = filePath.Substring(, filePath.LastIndexOf("/"))
If (Directory.Exists(dirPath) = False) Then
Directory.CreateDirectory(dirPath)
End If
Dim aa As System.IO.StreamWriter = New System.IO.StreamWriter(filePath, True, System.Text.Encoding.UTF8)
aa.WriteLine(log)
aa.Close()
aa.Dispose()
End SyncLock
End Sub
#End Region