我将我的应用程序更改为多线程应用程序。当我进行多线程处理时,由于尝试从多个线程读取文件的一个或多个应用程序出现错误Process cannot read the file because it's being use by another process.
这是我用来读取文件的类:
Imports System.Xml.Serialization
Imports System.IO
Public Class EmailSerializer
Public EmailConfig As New EmailConfig
Private ReadOnly _configPath As String = String.Empty
Public Sub New()
End Sub
Public Sub New(configPath As String)
_configPath = configPath
End Sub
Public Sub Add(emailConfig As EmailConfig)
Me.EmailConfig = emailConfig
End Sub
Public Function GetEmail() As EmailConfig
Return EmailConfig
End Function
Public Function GetSmtPip() As String
Return EmailConfig.Smtpip
End Function
Public Function Load(configPath As String) As EmailSerializer
Dim result As EmailSerializer
Dim streamReaderInstance As StreamReader
If (File.Exists(configPath)) Then
streamReaderInstance = New StreamReader(configPath)
End If
Dim xmlSerializer As New XmlSerializer(GetType(EmailSerializer))
Dim stringReader As New StringReader(streamReaderInstance.ReadToEnd())
result = DirectCast(xmlSerializer.Deserialize(stringReader), EmailSerializer)
stringReader.Close()
streamReaderInstance.Close()
EmailConfig = result.EmailConfig
Return result
End Function
End Class
这是我如何读取文件:
_emailSerializer = New EmailSerializer().Load(configEmail)
_emailSerializer.GetEmail()
第一行出错。
如果没有收到此类错误,该怎么办?
答案 0 :(得分:0)
您可以更改代码以创建StreamReader,以便它对文件使用只读访问权限。然后多个线程应该能够读取它。
streamReaderInstance = New StreamReader(File.OpenRead(configPath))