I have a simple question.
In my UWP app I am using multiple threads and while on a background thread when i try to create a simple BitmapImage by using code: var image=new BitmapImage();. It throws an exception
The application called an interface that was marshalled for a different thread.
this exception occurs on the very line where I try to create the image. I simply want to create this image, deal with its properties and then store it in my datalist.
Note: datalist is a simple public static property which is accesible throughout the app. thankyou
I can't see the full context from the question, so I am not sure why this exception is bubbling up, but one sure way to fix it is using CoreDispatcher.RunAsync().
The documentation says:
If you are on a worker thread and want to schedule work on the UI thread, use CoreDispatcher::RunAsync.
If you are using MVVMLight, you can also make use of it's DispatcherHelper class' CheckBeginInvokeOnUI method. It's a bit better, since it first checks which thread it is called on and if it's the UI thread, it executes the action immediately and passes it to the UI thread only if needed.
Related
I have a TClientDataSet that holds information and is not linked to any GUI component.
In a thread I locate the relevant record, go into edit mode and change the values. Because it happens inside a thread, I use TCriticalSection before locating until after posting. It looks something like that:
cs.Enter;
if not cds4Process.Locate('locator',locator,[]) then exit;
cds4Process.Edit;
cds4Process.FieldByName('field1').AsDateTime := pDay;
cds4Process.FieldByName('field2').AsFloat := amnt;
cds4Process.Post;
cs.leave;
cds4Process is located on the main form and it is not linked to any GUI component, I don't pass it as a parameter to the thread.
I execute the thread several times and in some point, I get an error that says that cds4Process is not in insert or edit mode. even though the above code sequence is the same in all the places I use cds4Process.
Any idea? What am I missing?
I would place everything related to the TClientDataSet (its connection component, persistent fields etc.) on a TDataModule instead on the main form, and then create an instance of this data module in the thread.
Using this thread-bound TDataModule as a container for data access components would allow visual design, and prevent me from using the VCL main thread accidentally.
I have a requirement to generate a bitmap out of an EditText and then perform some manipulations on it.
My main concern is not to call View.buildDrawingCache() method on the UI thread and possibly block it, especially when talking about large screens (i.e. Nexus 10) since the EditText will occupy about 80% of the available screen size.
I execute Runnables inside a ThreadPoolExecutor, those will inflate dummy views on a worker thread and set all the required attributes to them, then simply call buildDrawingCache() & getDrawingCache() to generate a bitmap.
This works perfect on some devices yet recently I have encountered a few devices that crash with the following message:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I understand why this happens, as some phones must have modified implementation for EditText that creates a Handler and thus requires Looper.prepare() to be called first.
From what I've read online there is no issue with calling Looper.prepare() inside a worker thread though some stated it is highly unrecommended yet I could not find a reason for that.
Other than that, most posts related to this issue state you are not supposed to inflate views inside a background thread, probably due to the following from Android's official documentation (Processes and Threads):
"Do not access the Android UI toolkit from outside the UI thread"
What is the recommended approach to dealing with this problem?
Is there any harm in calling build/get drawingcache from the main thread? (performance-wise)
Will calling Looper.prepare() inside my worker thread solve this problem?
EDIT
Just to elaborate on my specific requirement, I have a user-interface consisting of an ImageView and a custom EditText on top of it, the EditText can change it's font and color according to the user selection, it can be zoomed in/out using "pinch to zoom" gesture and can also be dragged around to allow the user to reposition it on top of the image.
Eventually what I do is create a dummy view inside my worker thread using the exact same values (width, height, position) it currently has on the UI and then generate it's drawingcache, the original image's bitmap is decoded again from a local file.
Once the two bitmaps are ready I merge them into a single bitmap for future use.
So to put it simple, is there anything wrong with executing the following code (from within a background thread):
Call Looper.prepare()
Create a new view with application context, call measure() & layout() manually and then build+get drawingcache from it, i.e.:
Looper.prepare();
EditText view = new EditText(appContext);
view.setText("some text");
view.setLayoutParams(layoutParams);
view.measure(
View.MeasureSpec.makeMeasureSpec(targetWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(targetHeight, View.MeasureSpec.EXACTLY));
view.layout(0, 0, targetWidth, targetHeight);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
How does this apply to the restriction with not accessing the Android UI toolkit from outside the UI thread, what could possibly go wrong?
In your case, you can do it of course, but be carefull only reading values from UI data, to avoid synchronizations bug.
Also you should not recreate the EditText from the background thread, it will be more efficient to directly access the already existant one instead:
Looper.prepare();
myEditText.setDrawingCacheEnabled(true);
Bitmap bitmap = myEditText.getDrawingCache();
If your question is : why it is not recommanded by android guidelines, here is a good SO answer to your question.
Calling View.buildDrawingCache() calls Bitmap.nativeCreate which can be a large allocation, so yes, it can be potentially harmful to run on main thread. I don't see a problem with calling Looper.prepare() in your background thread. However, it's unclear what you are trying to achieve and there may be a better solution to your problem.
The reason you are not supposed to the UI toolkit from other threads is that it is not written to be thread safe it is written under the assumption that only one thread runs it. This means it's really hard to tell what can go wrong, the bad effects, if any, will mostly happen in an un-repeatable due to specific timing of threads.
Your description of what you are trying to do it not too clear. In your case, I would just allocate a large bitmap, and draw text into it. Why are you using the EditText in the first place ? It seems like a kind of a hack, and hacks tend to break eventually.
Why View.buildDrawingCache()? What about using View.draw(Canvas canvas) to manually render to a Canvas backed by a Bitmap? Method seems simple enough to not cause problems on background threads.
EditText edit = (EditText)findViewById(R.id.edit);
edit.buildDrawingCache();
ImageView img = (ImageView)findViewById(R.id.test);
img.setImageBitmap(edit.getDrawingCache());
Lalit when you try to build the cache in the onCreate method, the drawing hasn't happened yet so the drawingCache should have nothing. Either put the buildDrawingChache method in the onClick method. Or use the following code in onCreate.
ViewTreeObserver vto = editText.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
editText.buildDrawingCache();
}
});
I also encountered this error a few times already:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
my solution:
new Thread(new Runnable(){
#Override
public void run(){
//add implementations that DOES NOT AFFECT the UI here
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run(){
//manage your edittext and Other UIs here
}
});
}
}).start();
just create a handler inside your worker thread to apply data changes to your UI
I'm using swing to display multiple javafx Tableview, each embeded (thanks to JFXPanel) in a swing TabbedPane
I use the well know pattern described in the oracle doc, in scala way :
implicit def fun2Run[T](x: ⇒ T) = new Runnable {
def run = x
}
def myTabbedScene():Scene = {
val root = new StackPane
root.getChildren.add(new Label("Hello world!"))
new Scene(root, 300, 300)
}
def initFxPanel(fxPanel: JFXPanel, s: ⇒ Scene) = {
fxPanel.setScene(s)
}
def initSwingGui(panel: PluginPanel) = {
val fxPanel = new JFXPanel()
// code to add panel to JPanel
panel.peer.add(fxPanel)
Platform runLater initFxPanel(fxPanel,myTabbedScene())
}
val jfxSwingPanel = new PluginPanel("wrap 2") {
var jtemp = new JPanel()
contents += jtemp
}
SwingUtilities invokeLater initSwingGui(jfxSwingPanel)
This code is executed each time the user open a new swing tab (only scene method differs) but i'm not sure this is the best way to manage thread in this case :-/
When i close or open a tab, i have some incoherent state in my application and error during display.
An example of my use case, and somes questions linked :
I open a first tab J1, a runlater is invoked, my scene display without problem in the tab.
I open a second tab J2, a new runlater is invoked on javafx Thread,
I switch to tab J1, how display in my tab is refresh ? An implicit runnable action is launched to main thread to make this possible ? How javafx recognized the good tab to refresh ? If i have a button which launch some action, i launch a runlater() action on the javafx main thread which dispatch ?
Update:
I find a code source which can help reader on this point, you can revalidate() or/and repaint() your swing panel (here _contentpane) which contain your jfxPanel
SwingUtilities.invokeLater(new Runnable() {
public void run() {
_contentPane.add(_jfxPanel);
_contentPane.revalidate();
_contentPane.repaint(); }});
I close the first tab J1, javafx automaticly close/garbage the javafx resource associated?
I have multiples other general questions :
How javafx application main thread manage this multiple runlater() call
when they arrive from different jfxpanel in swing ?
How can i close properly the resources (without close main javafx thread with exit() Platform method) associated to my jfxpanel when user close a tab ? If i destroy the JFXPanel,javafx resources used to display are liberated ?
Using task to manage my thread can be an answer to my problem ?
My question are probably naive, but i start in gui building, and i have problem to understand how javafx manage scene on different embedded panel.
How javafx application thread manage this multiple runlater() call when they arrive from different jfxpanel in swing ?
From the Platform.runLater javadoc:
Run the specified Runnable on the JavaFX Application Thread at some
unspecified time in the future. This method, which may be called from
any thread, will post the Runnable to an event queue and then return
immediately to the caller. The Runnables are executed in the order
they are posted. A runnable passed into the runLater method will be
executed before any Runnable passed into a subsequent call to
runLater.
Further:
How can i close properly the thread (without close main javafx thread) which execute my jfxpanel when user close a tab?
It's unclear which thread you are referring to. In general, when integrating JavaFX and Swing there are only two threads to be concerned with - the Swing dispatch thread and the JavaFX application thread - both of which should be managed by the respective underlying frameworks and you don't need to explicitly close. You don't need any other threads unless you are trying to do something which should not execute on either of those threads (such as a highly CPU intensive task or a remote I/O) - which from your sample code would not be appear to be the case.
Using task to manage my thread can be an answer to my problem ?
Unless you have a specific need for such a thing, such a solution would likely further complicate your situation than improve it.
I close the first tab J1, javafx automaticly close/garbage the javafx resource associated?
If you don't keep a reference to any of the resources in the related jfxpanel, then the Java Virtual Machine can garbage collect the jfxpanel and and resources associated with it - this is just standard Java garbage collection technology, nothing special here.
I switch to tab J1, how display in my tab is refresh ? An implicit runnable action is launched to main thread to make this possible ?
Sounds like a bad idea (the main thread in Java terms is the thread used to launch the Java's main function and is not involved in GUI programming at all). You probably want to submit your runnable refresh request via Platform.runLater() so that it will be executed on the JavaFX application thread.
How javafx recognized the good tab to refresh ?
You have a JavaFX JFXPanel in each swing tab and each swing tab knows which JFXPanel it has, so when you invoke Platform.runLater to refresh the specific panel, pass a (final) reference to the JFXPanel to be used. Here is some psuedo-code in no language whatsoever to illustrate the concept:
on swing tab change event
final JFXPanel curPanel = tab.getJFXPanel()
Platform.runLater() {
// update curPanel here...
}
If i have a button which launch some action, i launch a runlater() action on the javafx main thread which dispatch ?
In essence I think you are correct here, I'll just rewrite your question to clarify some of the terminology - let's say it's a swing button and on performing an action on the swing button, you make a call to Platform.runLater, then the code in the runLater call will be eventually be executed on the JavaFX application thread.
Other questions I cannot answer as I am not fluent enough in Scala to provide a reasonable answer.
Honestly, if you are just starting GUI building, then my unsolicited advice would be to use Java rather than Scala and stick with either Swing or JavaFX, but not mix it all together until you are really comfortable with the GUI building process - otherwise there are just way too many traps and pitfalls you may encounter during the integration that few will be able to assist you with.
I'm currently working on a program using MFC. The current third party function starts a thread after an action has been completed using MFC (ie. Checking a checkbox, which starts a MFC thread I believe).
The problem occurs when I check the checkbox, at which point the entire program hangs. I read a few interesting discussions on CProgramming and msdn, it seems that the problem occurs because the new third party thread is calling WaitToSomething() when MFC is updating a control.
Something interesting to note:
When I debug the program, the program hangs (aka. repeatedly calls WaitToRead() ) after I check the checkbox and a new thread is trying to start
When I run the program without debugger, the program is fine UNTIL I switch to another window (ie. Internet browser, Notepad, etc)
My hypothesis:
check to make sure that MFC has finished updating the control before starting a new thread
If anyone has any suggestions or solutions, please leave a comment. Thanks.
Edit:
MFC is not thread-safe at object level (only at class level), so problem occurs when two threads work on the same CButton object.
Q: How do I make it thread safe?
A colleague helped me figure out what the problem was.
The reason why it was hanging is because that the control containing the checkbox is a child dialog, and when it finished updating the message never got passed up to its parent (so when 3rd party thread calls WaitFor(), the MFC thread never completes because a parent dialog thinks its child is still updating the controls).
Fix:
Under 'Properties' in the child dialog's control, set the 'Control' flag to true (and if it has children, set the 'Control Parent' flag to true as well).
Hope this helps.
I have a TThread which receives and sends to a device on a COM port. After I read the data, I want to activate the GUI (not in the same thread) using Synchronize(function name). However, when I call the GUI's form function to perform a button click, I get an access violation. I checked to see if the form's value is null and it is not, since this would be an obvious reason for access violation. Right now, I am setting global flags and using a timer that continuously checks to see if a certain condition is met and if so, then I fire off the button click event in that form. That seems to be the only way to avoid getting the access violation.
I really don't like timers so is there a way to avoid having to use a timer on the form?
You can post a message to the window in question. The timer works in a similar manner. It just fires off a windows message inside the form. You obviously have a handle to the window.
CWnd::PostMessage(...) Don't use send message, it gets processed inline and could cause your thread to stop working.
Typically when you have a worker thread that attempts to access Guithread, they conflict. It's been a while since I've used MFC and threading but that's what I remember. I believe it's documented to work that way.
I found the problem. I thought I was checking if my Form was null, but I was not. I fixed it making sure the form I was referencing is not null.
Edit: Turns out that one of the forms that is called when I call Fbutton1Click() is Modal so it blocks my thread. I ended having to go back to a timer to call the button click instead.. oh well.