I have a program that must copy a file to 3 locations, the local hard disk, a USB drive, and a network location. I have the file (about 70mb) loaded into a byte array. My quesion is, since I'm not actively modifying the byte array, can I impliment a form of multithreading where all 3 threads read the same byte array at the same time?
Xcelled194 28 Junior Poster in Training
Unhnd_Exception
Heres the directions for thread safety on the array class:
Thread Safety
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
This implementation does not provide a synchronized (thread safe) wrapper for an Array; however, .NET Framework classes based on Array provide their own synchronized version of the collection using the SyncRoot property.
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
From reading that it looks like you would be ok as long as you didn't modify the array.
I put together an example to test and everything appears ok.
Option Strict On
Public Class Form1
Private ByteArrayToReadFrom(40000) As Byte
Private Delegate Sub SaveByteArrayDelegate(ByVal fileCount As Integer)
Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
Randomize()
' Add any initialization after the InitializeComponent() call.
For i = 0 To UBound(ByteArrayToReadFrom)
ByteArrayToReadFrom(i) = CByte(Rnd() * 255)
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Thread1 As SaveByteArrayDelegate
Dim Thread2 As SaveByteArrayDelegate
Dim Thread3 As SaveByteArrayDelegate
Dim FileCount As Integer
For i = 1 To 1000
Thread1 = New SaveByteArrayDelegate(AddressOf SaveByteArray)
Thread2 = New SaveByteArrayDelegate(AddressOf SaveByteArray)
Thread3 = New SaveByteArrayDelegate(AddressOf SaveByteArray)
Thread1.BeginInvoke(FileCount + 1, Nothing, Nothing)
Thread2.BeginInvoke(FileCount + 2, Nothing, Nothing)
Thread3.BeginInvoke(FileCount + 3, Nothing, Nothing)
FileCount += 3
Next
End Sub
Private Sub SaveByteArray(ByVal fileCount As Integer)
Try
My.Computer.FileSystem.WriteAllBytes(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\Garbage\File" & fileCount & ".txt", ByteArrayToReadFrom, False)
Catch ex As Exception
End Try
End Sub
End Class
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.