I have got a program which is controlling a video capturing card. And this card has got several inputs and my task is to write a method which starts capturing from all inputs. Unfortunately in SDK I can only call the method which handles a click event for one button. I've got an idea to write a few threads which simultaneously call this method for each button which is presented by specified input.
Below this is my thread. I call and give a reference of the button which is selected to start.
private class StartThread
{
private static DateTime startTime; //arbitrary start time
private Button btnStart;
public static void initializeTimer()
{
startTime = DateTime.Now.AddSeconds(5); //arbitrary start time
}
public StartThread(Button btnTmp)
{
this.btnStart = btnTmp;
}
public delegate void DelegateStandardPattern();
public void doWork()
{
while (DateTime.Now < startTime) ;
btnStart.PerformClick();
}
};
There I check if the specified start button should start and create the thread:
private void btnStartAllClick(object sender, EventArgs e)
{
int i = 0, j = 0;
List<Thread> listThreads = new List<Thread>();
for (i = 0; i < miInstalledCardNum; i++)
{
for (j = 0; j < mCard[i].iDeviceNum; j++)
{
if (mCard[i].Device[j].ChkBoxStartAll.Checked == true &&
mCard[i].Device[j].ChkBoxStartAll.Enabled == true)
{
StartThread tmpThread = new StartThread(mCard[i].Device[j].BtnStart);
listThreads.Add(new Thread(tmpThread.doWork));
}
}
}
if(listThreads.Count > 0){
StartThread.initializeTimer();
foreach(Thread currentThread in listThreads)
currentThread.Start();
foreach (Thread currentThread in listThreads)
currentThread.Join();
}
}
Unfortunately this operation returns an exception:
Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
I tried witch InvokeRequired
:
if (this.InvokeRequired)
{
this.Invoke(
new MethodInvoker(
delegate() { ThreadSafeFunction(intVal, boolVal); }));
}
else
{
//use intval and boolval
}
But I get another error:
does not contain a definition for 'Invoke' and no extension method 'Invoke' accepting a first argument of type 'fmb_player_apl.MasterForm.StartThread' could be found (are you missing a using directive or an assembly reference?)
I must start four button parallel, because it causes asynchronous video.