I need to spawn several background threads for the ThreadPool (my test store contains 6008 part numbers, and the individual threads would look up each part's barcode and description from the corporate database).
I am getting ideas from this post: Wait for pooled threads to complete
I am interested in trying JaredPar's answer without the WaitHandle (since it has a 64 thread limit), but I don't know how to duplicate his QueueUserWorkItem in this VB application:
public static void SpawnAndWait(IEnumerable<Action> actions)
{
var list = actions.ToList();
var handles = new ManualResetEvent[actions.Count()];
for (var i = 0; i < list.Count; i++)
{
handles[i] = new ManualResetEvent(false);
var currentAction = list[i];
var currentHandle = handles[i];
Action wrappedAction = () => { try { currentAction(); } finally { currentHandle.Set(); } };
ThreadPool.QueueUserWorkItem(x => wrappedAction());
}
WaitHandle.WaitAll(handles);
}
How would x => wrappedAction()
be written in VB?
It seems like a simple task, but I cannot find any information on how to convert it.
Below is a little VB stub I wrote, trying to get this working.
Using what someone found in Invoke anonymous methods, I tried writing it different ways.
Private m_db As DatabaseHelper
Public Sub Test1(store As StoreLocation)
For index As Integer = 0 To store.Parts.Count - 1
Dim item As StorePart = store.Parts(index)
Dim job As New Action(
Sub()
Dim lines As String() = m_db.GetDetails(store.ID, item.PartNumber)
item.UPC = lines(0)
item.Vendor = lines(1)
item.Description = lines(2)
End Sub
)
ThreadPool.QueueUserWorkItem(job()) ' See 1.
ThreadPool.QueueUserWorkItem(job.Invoke()) ' See 2.
ThreadPool.QueueUserWorkItem(job) ' See 3.
Next
End Sub
No, it does not compile.
- Expression does not produce a value
- Expression does not produce a value
- Value of type 'System.Action' cannot be converted to 'System.Threading.WaitCallback'
This project compiles to .NET 4.0, so I can't really use 4.5 await features unless plugins are authorized for the corporate project.