Application.DoEvents() and GC.WaitForPendingFinalizers() - multithreading

I have downloaded a code from the internet and this is a few lines of it.
//Notification
lblUpdate.Text = String.Format("Loading Master File {0}...",
fMaster);
Application.DoEvents();
/// File Load Phase
while (!bLoaded)
{
try
{
bMaster = new Bitmap(fMaster);
bLoaded = true;
}
catch (OutOfMemoryException)
{
GC.WaitForPendingFinalizers();
}
}
in this code:
bloaded is a boolean
bMaster is a bitmap
fMaster is a string
My questions are the following :
1- What does Application.DoEvents(); do?
2- What does GC.WaitForPendingFinalizers(); do?
Please take into consideration that I've done research on google and did not understand , need easy to understand yet detailed explanations if possible.
Thank you for all in advance.

Related

How I can resolve this error in Katalon Groovy:unexpected token: do // Groovy:unexpected token: if // Groovy:expecting EOF, found 'if'

// Read data from XML file
public static String getElementTextByTagName(String tagName) {
try {
String dirPath = System.getProperty('user.dir') + "\\DataFiles\\TestData.xml"
List<File> xmlFiles = getXMLFilesByDirectory(dirPath);
Iterator var3 = xmlFiles.iterator();
XMLSearchResult searchResult;
do {
if (!var3.hasNext()) {
throw new ElementNotFoundInXMLException("Element Not Found");
}
File xmlFile = (File)var3.next();
searchResult = searchForElementInsideFile(xmlFile, tagName);
} while(!searchResult.isFound());
return searchResult.getElementText();
} catch (ElementNotFoundInXMLException var6) {
var6.printStackTrace();
return null;
}
}
enter image description here
The error is appearing on the do statement line and below the same for if statement
Katalon Studio uses a version of Groovy, at the time of this answer, that does not support do-while loops.
For that effect, you'll have to do something like what's outlined in this question.
Consider it a professional courtesy that I take the time to link the answer here, instead of voting to close the question because it's already answered by that other question.
Welcome to StackOverflow.

What causes "Variable does not exist in current context" message

I'm trying to write a very simple C# program in VS2015. I keep getting a message "The name (variable) does not exist in the current context." This is true for both my bool variable and string variable.
namespace PTouch
{
public class PTouch
{
bool lb_rc;
string strLabel;
lb_rc = false;
strLabel = "C:\BenchTop10\Standard 1in.lbx";
bpac.Document doc = new Document();
lb_rc = doc.Open("C:\BenchTop10\Standard 1in.lbx");
if lb_rc != false
{
doc.StartPrint("", 0);
doc.PrintOut(1, 0);
doc.EndPrint();
doc.Close();
}
else
{
MessageBox.Show("Open Error: " + doc.ErrorCode);
}
}
}
There are probably several problems with this code, but the first one is error about the variables not existing in the current context.
Any assistance is greatly appreciated.
I just discovered the problem... All the code has to be inside of a method, not just the class. I added a method to the class,
public void PrintLabel()
{ bool lb_rc; ... }
All errors cleared up, except MessageBox...
Thank you,
Tracy

Close CameraDevice in a seperate thread

I am using Android camera2 to create a custom camera. The cameraDevice.close() method is slow and it makes UI freeze for 1 sec. I put it in another thread and it seems to work just fine. I want to know if this will cause some serious problem and whether there is another way to achieve this. Here is my closeCamera method:
private void closeCamera() {
boolean release = false;
try {
mCameraOpenCloseLock.acquire();
release = true;
} catch (InterruptedException e) {
release = false;
}
try {
preparing = true;
if (mCaptureSession != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && mCaptureSession.isReprocessable()
|| validCameraSession) {
mCaptureSession.close();
}
mCaptureSession = null;
validCameraSession = false;
}
} catch (IllegalStateException e) {
mCaptureSession = null;
} catch (Exception e) {
mCaptureSession = null;
}
try {
new Thread(new Runnable() {
#Override
public void run() {
if (mCameraDevice != null) {
if (openCamera) {
mCameraDevice.close();
mCameraDevice = null;
}
}
}
}).start();
} catch (IllegalStateException e) {
Log.e(TAG, "closeCamera: mCaptureSession - ", e);
} catch (Exception e) {
Log.e(TAG, "closeCamera: mCaptureSession - ", e);
}
if (release) {
if (mCameraOpenCloseLock != null) {
int lock = mCameraOpenCloseLock.availablePermits();
if (lock > 1) mCameraOpenCloseLock.release(lock - 1);
else if (lock == 0) mCameraOpenCloseLock.release();
}
}
}
I think it may cause crash when mCameraDevice has not been closed but user open camera again. But it is rare case, and I am thinking of putting another check before open camera again. I don't want my UI to freeze 1 sec for it to close, is there any other way I can achieve that except putting it in seperate thread?
As Alex Cohn mentions, the recommended practice is to do all camera-related work on a separate thread from the UI.
It also takes a long time to open the camera, or create a capture session, relatively speaking, so doing those operations not on the UI thread is also a good idea.
That said, as long as you're not losing track of your own app state (so that you don't try to use a camera device you've already closed by accident, for example), there's no reason you can't mix calls to the camera device or capture session from multiple threads. The classes themselves are thread-safe.
As far as I know, such freeze with cameraDevice.close() happens on some unfortunate devices, and sometimes is cured by performing a normal system upgrade.
But this is a little consolation if this happens to you, on your device. Actually, you are kind of lucky that you can prepare a fix for that. The end-users of your app will benefit from your misfortune.
Your code looks OK, if it delivers desired improvements for you. As I explained, it may be hard to reproduce this problem on another device.
I would rather put all closeCamera() logic on the same background thread. If you provided a Handler to openCamera(), as in the official example,
manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
then I would suggest posting all closeCamera() sequence to this mBackgroundHandler.

sony camera api cardboard application

I want to make an application for cardboard with a sony actioncam. I noticed that we can get the video preview by a SurfaceView method. But I remember that the only way to have a split screen with the camera device is by a SurfaceTexture.
So my question is, is there a way with one actioncam to have 2 video previews simultaneously ( split screen ) ??
thanks
EDIT:
okay so I went ahead and bought an action cam AS200, the sdk sample worked perfectly and i was able to get the video preview very quickly. I tried to duplicate the SimpleStreamSurfaceView with no success as expected. Now I m trying to copy the byte array in order to have two previews in one array. First I have tried to simply create an arraybuffer where i put two times the bitmap array, just to see what changes ... and I was surprised to see that nothing changed ... Here is the code
`
while (mWhileFetching) {
try {
byte[] jpegData = mJpegQueue.take();
ByteBuffer test=ByteBuffer.allocate(jpegData.length *2);
test.put(jpegData);
test.put(jpegData);
frameBitmap = BitmapFactory.decodeByteArray(//
test.array(), 0, test.array().length, factoryOptions);
//frameBitmap.setWidth(frameBitmap.getWidth()*2);
} catch (IllegalArgumentException e) {
if (mInMutableAvailable) {
clearInBitmap(factoryOptions);
}
continue;
} catch (InterruptedException e) {
Log.i(TAG, "Drawer thread is Interrupted.");
break;
}
if (mInMutableAvailable) {
setInBitmap(factoryOptions, frameBitmap);
}
drawFrame(frameBitmap);
}
if (frameBitmap != null) {
frameBitmap.recycle();
}
mWhileFetching = false;
}
};
mDrawerThread.start();
return true;
}
`
Of course I wasnt expecting a great result but why nothing changed ??
I solved it. I just had to draw two times in the canvas to different rectangles.

Cannot open a word doc and reference it without locking it

Hello I know how to open and get plain text from a word file for a bit of code. However I am having a bad effect occur from this. The word doc becomes locked and I am not aware how to de allocate whatever is locking it. What I ultimately want would like to open a file that will be in a UNC path and read part of it, whether someone else has it open or not, parse lines from it, close it, don't save anything or lock the file. The closest I can get is I can open a file, parse it, it will lock, but when I open it and close it(same machine running the code) it magically unlocks it.
I know almost nothing on COM so I hunted for a while and found something out about the Marshall object and added that. I have tried to turn on and off the reference 'ReadOnly: True', 'ReadOnly: False'. I feel there is just something simple I am missing so I thought I would ask here. Any suggestions feel free, I am coding in .NET 4.0 so you don't have pass in all those annoying obj = null, obj = null for opening the Doc.
public static string ReadWordDoc(string loc)
{
Word.Application wordApp = new Word.Application();
Word.Document Doc = wordApp.Documents.Open(loc, ReadOnly: true);
sb = "";
foreach (Word.Paragraph objParagraph in Doc.Paragraphs)
{
try
{
sb += objParagraph.Range.Text + "\n";
}
catch (Exception ex)
{
throw ex;
}
}
return sb;
Doc.Close(SaveChanges: false);
Marshal.ReleaseComObject(Doc);
wordApp.Quit(SaveChanges: false);
}
I figured it out for some reason a lock was being kept. I made sure I quit the Word app with 'Do Not Save Changes' as well as running the Garbage Collector as well. It may be a little overkill but it essentially ensures that no lock is left on my file I am targeting.
Word._Application wordApp = new Word.Application();
Word._Document Doc = wordApp.Documents.Open(loc, ReadOnly: true);
try
{
sb = "";
foreach (Word.Paragraph objParagraph in Doc.Paragraphs)
{
try
{
sb += objParagraph.Range.Text + "\n";
}
catch (Exception ex)
{
throw ex;
}
}
}
catch (COMException) { }
finally
{
//FileInfo finfo = new FileInfo(loc);
//finfo.IsReadOnly = false;
if (Doc != null)
{
Doc.Close();
Doc = null;
}
if (wordApp != null)
{
wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
wordApp = null;
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return sb;

Resources