Can I run Service in background thread?
I want to load data from database and during loading data i want progress bar to be indicating progress. First I have created task, run it in background thread and then update progress bar according to this task. However, I found out that this Task is not reusable, so next time i hit the button, it didn't work. Later on, I fount out that Service can run Tasks multiple times, So i have encapsulated those tasks inside of Service.
Now it works great - every time i hit button, table is reloaded - except progress bar is not moving.
How can I reach desired result?
Okay... Here is completed code: https://mega.nz/#!yUsjgJyZ!DHfuBqsujAHurS-pQ_W5y8BAflOtvxsm48goRPkDsxA
First, i want to tell you what is my goal:
When I run program, i want the progress bar to be in indeterminate state. After pressing the button, i want progress bar to reflect progress of Service. After finishing the Service, i want the progress bar to be completed (100%).
Here is what i have found. It looks like service automatically runs it's task on background thread. I have built a "sand box" program where i was playing with services and progress bar. The program comprised of progress bar, two text fields with two buttons above them. First button can start service_countTo100 and second button can run service_getActualCount.
Now in fxml file i set progress bar to indeterminate default state. After pressing the button1, a counting has started (displayed in text_field1) and progress bar has changed according to actual progress. After pressing button2, actual value of count is displayed in text_field2. And here comes some issues. To demonstrate the issues, i will show you source code of Service:
// Create the service
public static Service<Integer> serviceTo100 = new Service<Integer>() {
#Override
protected Task<Integer> createTask() {
Task<Integer> taskTo100 = new Task<Integer>() {
#Override protected Integer call() throws Exception {
int iterations;
updateProgress(-1, 100);
for (iterations = 0; iterations < 100; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, 100);
// Now block the thread for a short time, but be sure
// to check the interrupted exception for cancellation!
try {
Thread.sleep(100);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
//udpateProgress(100, 100);
return iterations;
}
};
return taskTo100;
}
};
As you can see, there is a simple loop which counts from 0 to 100 and there is also a updateProgress(iterations, 100); statement which updates progress. This service is located in Services class. In FXMLDocumentController.java is method called runService(Service service) defined as this:
public void runService(Service service){
service.start();
progressBar.progressProperty().bind(service.progressProperty());
service.setOnSucceeded((event) -> {
service.reset();
progressBar.progressProperty().unbind();
progressBar.setProgress(1);
});
}
The initialize looks like this:
#Override
public void initialize(URL url, ResourceBundle rb) {
btn_start1.setOnAction((event) -> {
Service service = Services.serviceTo100;
runService(service);
txt_field1.textProperty().bind(service.messageProperty());
System.out.printf("something\n");
});
.
.
.
}//end of initialize
Now the most interesting thing (at least for me, novice) comes into play.
In service definition, you can notice commented line //updateProgress(100,100). That was my try to set progress bar to completed state when counting has stopped. But java ignored that line. I tried to put System.out.print("Something"); and it worked, but updateProgress(100, 100) didn't. When counting has finished, progress bar was set to it's default state defined in fxml file, which was indeterminate.
Conclusion: Service class creates task defined inside of it and after task is completed, the task doesn't exists anymore, thus, there is no progress to be bound with progress bar.
Even though task does not exists anymore, you cannot set progress of the bounded progress bar with setProgress(double double) method. You first need to unbound it.
Now I got what i needed:
You run the program, progress bar is in indeterminate state, waiting for hit. You hit the button, service starts counting up to 100 and progress bar is progressing according to progressProperty of service. When counting is done, Progress bar is set to indeterminate state again, waiting for another start.
Related
I am working on web application. In which i am stuck with some issue.
When i call some server function it will take time to get response. When response have high number of data. It will get data, process on that data and update GUI in background.
Upto that my application GUI freeze. I can not click on any part. I see some where that ActionScript support multithreading. I found some tutorial for that which is here. But, it is for desktop application only.
Is there any way i can handle this freezing of application/GUI in web application. It will decrease my application performance and looks very bad.
Example:
If i have list of data with checkbox and on checkbox click there is some process. Now, there is one button called "Select All". Now, if i click on "select all" then all check box selected and process on check selection is going and freeze the application upto process done.
like: I have following list
<s:List id="tempList" itemRenderer="CustomItemRenderer"
dataProvider="{someList}" useVirtualLayout="false"/>
ItemRenderer have label and checkbox as following.
<s:CheckBox id="cCheckId" selected="{data.selected}"
change="onChangeHandler(event)" />
<s:Label id="lblTest" />
protected function onChangeHandler(event:Event):void
{
data.selected = !data.selected;
}
Now, on button Select all will select all check box.
<s:Button id="btnSelectAll" label="Select All" click="selectAllHandler(event)" />
protected function selectAllHandler(event:MouseEvent):void
{
for(var i:int = 0;i<someList.length;i++)
{
someList[i].selected = true;
}
}
Now, if someList have lots of data then it will freeze the screen.
Any help is greatly appreciated.
The main idea behind the list and itemrenderers that you have a list (or datagrid) that displays like 30 items and then you can scroll to see the rest. Then you will only have 30 Itemrenderers that would be updated at once.
If you don't want to scroll you will need to distribute your item selection over several frames, something like that (untested, but you get the idea)
private static const ITEMS_AT_ONCE:int = 5000;
private var _currentIndex:int;
protected function selectAllHandler(event:MouseEvent):void
{
_currentIndex = 0;
addEventListener(Event.ENTER_FRAME, onEnterFrame); // this will call the onEnterFrame method on each frame rendered
}
private function onEnterFrame(e:Event):void
{
// make sure we don't run out of bounds of the dataprovider's length
var maxIndex:int = Math.min(_currentIndex + ITEMS_AT_ONCE, someList.length);
// set selection for the current bunch
for (var i:int = _currentIndex; i < maxIndex; i++)
{
someList[i].selected = true;
}
if (maxIndex == someList.length)
{
// We are done, remove enterframe listener
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
// I'm not sure but don't you need to refresh the dataprovider to reflect the changes in the ItemRenderers ?
// (someList.dataProvider as ArrayCollection).refresh();
}
else
{
// update the _currentindex so we continue after this item on the next frame
_currentIndex = maxIndex;
}
Another possible solution - if you display all of them anyways - you might try to switch to a VGroup that will hold custom UIComponents (without MXML) for the items - this should speed up the rendering.
I need to get data from a API I’ve used debug prinln’s and these print almost instantly including the information gotten from the API, but when I try to display this info to the user in the ViewController this takes around 30 seconds to display.
I will get the information from the API here
func httpGet(request: NSURLRequest!, callback: (NSData?, String?) -> Void) {
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
callback(nil, error.localizedDescription)
} else {
callback(data, nil)
}
}
task.resume()
}
I invoke the request and return a string for debugging
func loadSchedule() {
httpGet(request) {
(data, error) -> Void in
onComplete(“Milo Cesar”)
}
And here I will display the data to the user
#IBAction func settingsButtonPress(sender: AnyObject) {
println("Settings Button Pressed: Invoking Schedule")
Schedule().loadSchedule(){
(scheduleData) in
println("Found Schedule: Setting Title to \(scheduleData)")
self.settingsButton.setTitle(scheduleData, forState: UIControlState.Normal)
}
}
The whole process from the “Settings Button Pressed: Invoking Schedule” statement in my console till I get “Found Schedule: Settings Title to Milo Cesar” takes less than a second.
Since the name already gets displayed in that console log I think that the information has been loaded. Though it takes up to 35 seconds for the Button to change it’s title.
Why does it take so long for my UIButton to update it’s title after the data has been retrieved?
Are you sure you are updating its title in main thread? try to wrap it up in GCD
dispatch_async(dispatch_get_main_queue()){
self.settingsButton.setTitle(scheduleData, forState: UIControlState.Normal)
}
EDIT
it fixes it because everything UI related must be performed by main thread, its a restriction that comes directly from Apple. You can use background threads for long taking tasks(download data, perform long taking calculations or sort large arrays) but everything that needs to be displayed on your screen must be performed by main thread(tableview reload, animations, inserting text into label).
Also here is a great tutorial on GCD and its functionality: http://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1
I am having a child window derived from CFormView. On certain condition in OnCreate() function, I want to close this window.
I tried 2 options:
int CFilterWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFormView::OnCreate(lpCreateStruct) == -1)
return -1;
//Trial-1
if (!IsInitialized())
{
DestroyWindow();
return 0;
}
//Trial-2
if (!IsInitialized())
{
return -1;
}
return 0;
}
In both scenarios, the window is closed but my system returns "Failed to create empty document."
How do I avoid this message?
This is a completely normal behavior.
Document, Frame and View are created in one turn. First the document is created, than the frame and than the inner view. If one of the operations failed all other are also rolled back and fail.
So in the case of the MDI OnFileNew calls OpenDocumentFile from you template.
This function creates the new CDocument, followed by a new frame window. The frame window creates the view. This fails due to your code.
Your error message comes from CMultiDocTemplate::OpenDocumentFile because CreateNewFrame fails.
Let the MFC create your window and destroy the view it in OnInitialUpdate. This should work without this message.
Ok, I'm working on my final dilemna for my project. The project is an IPv4 endpoint updater for TunnelBroker's IPv6 tunnel. I have everything working, except for the timer. It works, however if the user disables the "automatic update" and reenables it, the application crashes. I need the timer to be on an thread outside of the EDT (in such a way that it can be destroyed and recreated when the user unchecks/checks the automatic update feature or changes the amount of time between updates).
What I'm pasting here is the code for the checkbox that handles automatic updates, and the timer class. Hopefully this will be enough to get an answer on how to do this (I'm thinking either it needs to be a worker, or use multi-threading--even though only one timer will be active).
private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
// if selected, then run timer for auto update
// set time textbox to setEditable(true) and get the time from it.
// else cancel timer. Try doing this on different
// class to prevent errors from happening on reselect.
int updateAutoTime = 0;
if (jCheckBox1.isSelected())
{
updateAutoTime = Integer.parseInt(jTextField4.getText())*60*1000;
if (updateAutoTime < 3600000)
{
updateAutoTime = 3600000;
jTextField4.setText(new Integer(updateAutoTime/60/1000).toString());
}
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run()
{
// Task here ...
if (jRadioButton1.isSelected())
{
newIPAddress = GetIP.getIPAddress();
}
else
{
newIPAddress = jTextField3.getText();
}
strUsername = jTextField1.getText();
jPasswordField1.selectAll();
strPassword = jPasswordField1.getSelectedText().toString();
strTunnelID = jTextField2.getText();
strIPAddress = newIPAddress;
if (!newIPAddress.equals(oldIPAddress))
{
//fire the tunnelbroker updater class
updateIP.setIPAddress(strUsername, strPassword, strTunnelID, strIPAddress);
oldIPAddress = newIPAddress;
jLabel8.setText(newIPAddress);
serverStatus = updateIP.getStatus().toString();
jLabel6.setText(serverStatus);
}
else
{
serverStatus = "No IP Update was needed.";
jLabel6.setText(serverStatus);
}
}
}, 0, updateAutoTime);
}
else
{
updateTimer.cancel();
System.out.println("Timer cancelled");
System.out.println("Purged {updateTimer.purge()} tasks.");
}
}
As I mentioned, this works once. But if the user deselects the checkbox, it won't work again. And the user can't change the value in jTextField4 after they select the checkbox.
So, what I'm looking for is this:
How to make this so that user can select and deselect the checkbox as they want (even if it's multiple times in a row).
How to make this so the user can change the value in jTextField4, and have it automatically cancel the current timer, and start a new one with the new value (I haven't done anything with the jTextField4 at all, so I'll have to create an event to cover it later).
Thanks, and have a great day:)
Patrick.
Perhaps this task would be better suited to a javax.swing.Timer. See Timer.restart() for details.
Note that Timer is relatively inaccurate over long time periods. One way to account for that is to have it repeat frequently but perform it's assigned task only one a certain time has been reached or passed.
Would I be able to wrap everything in the "task" portion of the call to Swing Timer, or do I have to create another class that handles the task?
You might want to wrap the grunt work in a SwingWorker to ensure the EDT is not blocked.
..I'm assuming that I would have to create the timer as a class-level declaration .. correct?
Yes, that is what I was thinking.
In short:
I want to show a view or action sheet and only continue code execution after the user has dismissed the view / sheet. So: line one shows the view, line two reads some result variable.
In detail why I would need this:
I'm porting a Windows Forms application over to the iPad. The original implementation has a communication class which uses a web service to communicate with the server. It offers a couple of methods to get data. Conveniently it checks prior to each call if the user still has a valid connection or if he has to re-enter his password for security reasons.
If the password is required, the .NET class shows a modal dialog which blocks any further code executio and if the password was entered, retries the last call it has made before showing the dialog.
Now using CocoaTouch I'm facing a problem. I replaced the code that shows the dialog with a UIActionSheet. Works great but code execution continues immediately, whereas in Windows Forms it is blocked (the next line in Windows Forms after showing the dialogs is to read the entered password from the dialog) until the dialog has been closed.
I tried a Thread.Sleep() until the user dismisses the UIActionSheet but the Thread.Sleep() also blocks the main loop and my view won't even be drawn.
The alternative I currently see is to change all methods in the already working class and give them a return value: if password required, handle it, then retry.
But this means that all over my code I will have to add these checks because at any given moment the password might be needed. That's why it is nested in communication class in Windows Forms.
Any other ideas?
René
Yes, it is possible.
To do this, what you can do is to run the mainloop manually. I have not managed to stop the mainloop directly, so I instead run the mainloop for 0.5 seconds and wait until the user responds.
The following function shows how you could implement a modal query with the above approach:
int WaitForClick ()
{
int clicked = -1;
var x = new UIAlertView ("Title", "Message", null, "Cancel", "OK", "Perhaps");
x.Show ();
bool done = false;
x.Clicked += (sender, buttonArgs) => {
Console.WriteLine ("User clicked on {0}", buttonArgs.ButtonIndex);
clicked = buttonArgs.ButtonIndex;
};
while (clicked == -1){
NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5));
Console.WriteLine ("Waiting for another 0.5 seconds");
}
Console.WriteLine ("The user clicked {0}", clicked);
return clicked;
}
I think this approach using async/await is much better, and doesn't suffer from freezing the app when rotating the device, or when the autoscrolling interferes and leaves you stuck in the RunUntil loop forever without the ability to click a button (at least these problems are easy to reproduce on iOS7).
Modal UIAlertView
Task<int> ShowModalAletViewAsync (string title, string message, params string[] buttons)
{
var alertView = new UIAlertView (title, message, null, null, buttons);
alertView.Show ();
var tsc = new TaskCompletionSource<int> ();
alertView.Clicked += (sender, buttonArgs) => {
Console.WriteLine ("User clicked on {0}", buttonArgs.ButtonIndex);
tsc.TrySetResult(buttonArgs.ButtonIndex);
};
return tsc.Task;
}