I have a multithreading program with 2 threads.
One thread is detecting the USB insertion and removal.
The second thread is responsible for transferring files to the USB (on USB insertion event). Once all the files are successfully copied to the USB then, the File Copying Thread (second thread) should enter into the “Successfully Copied” state and remain there till the USB is removed. As soon as the USB is removed, the isUSBInsterted
flag is set to FALSE and the File Copying Thread (second thread) enters into the IDLE state.
public enum FileTransferStates { Idle = 0, FileCopyingState = 1, SuccessfullyCopiedState = 2 }
public void ExecuteUSBFileTransfer()
{
switch (CurrentState)
{
case FileTransferStates.Idle:
IdleState();
return;
case FileTransferStates.FileCopyingState:
FileCopyingState();
ExecuteUSBFileTransfer();
break;
case FileTransferStates.SuccessfullyCopiedState:
SuccessfullyCopiedState();
ExecuteUSBFileTransfer();
break;
default:
return;
}
}
private void SuccessfullyCopiedState()
{
//Current state is "FileTransferStates.SuccessfullyCopiedState"
if (!USB.isUSBInsterted)
CurrentState = FileTransferStates.Idle; //Resetting the State if the USB is removed
}
QUESTION: Currently, I am calling the parent method (ExecuteUSBFileTransfer()
) again and again, if the thread has entered into SuccessfullyCopiedState()
. I think this is a wastage of CPU resources. Moreover, a USB may remain inserted for very long periods. So, I would like that the thread sleeps for this duration until the USB is not removed. How can I remain in SuccessfullyCopiedState()
and not check for the USB removal without wasting resources?
PS: Basically, I want to send the File Copying Thread into dormant stage inside the SuccessfullyCopiedState()
method till the USB is not removed.