What happens to background thread if timers are stopped or UI is reloaded c++ winrt - winrt-xaml

I have some timers as member :
Windows::UI::Xaml::DispatcherTimer^ m_pollingTimer;
I create the timer as below and on timer tick i execute some async task :
m_pollingTimer = CreateAndStartDispatcherTimer(500ms, &MainPage::OnPollingTick);
While reloading/suspending application i stop the timers as below :
Stop all timers :
for (auto timer : {m_pollingTimer})
{
if (timer)
timer->Stop();
}
What happens to background tasks if I stop the timer itself?
- Does it stop the background tasks as well or waits for the task to finish?
Reload Application :
bool MainPage::Reload(Platform::Object^ param)
{
auto rootFrame = dynamic_cast<Windows::UI::Xaml::Controls::Frame^>(Window::Current->Content);
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == nullptr)
{
// Create a Frame to act as the navigation context and associate it with
// a SuspensionManager key
rootFrame = ref new Windows::UI::Xaml::Controls::Frame();
}
auto type = rootFrame->CurrentSourcePageType;
try
{
return rootFrame->Navigate(type, param);
}
catch (Platform::Exception^ ex)
{
throw ex;
}
}
After stopping the timers i reload the UI.
Will the background thread keep running or stopped already?

Existing threads will be suspended with the rest of the application. As noted in the comments, no new timer events will be raised since you manually called Stop on them.
If you have work that you want to complete before your app is suspended, you should take a Deferral on the Suspending event and then only Complete it once your background work is complete.
That ensures you won't freeze a background thread half-way through its work and then wake it up again later whilst simultaneously running your reload code. That could easily cause race conditions. Also your background work should poll periodically to see if suspension is pending and thus it should try to terminate early.

Related

Lightswitch task on a background thread

I have a lightswitch app which sends an email when a new job is added. I added a sendemail helper class which is called when the record is inserted.
This works however the interface hangs on save waiting for the email to be sent.
I would like to perform this asychronously so that the user can go on and do his thing while the email sends in the background.
I've tried creating a new thread in the inserted part, hoping it would spin off the thread and then return to the user, but it doesn't work, it is still waiting for the thread to finish.
Thread caseemail = new Thread(new ParameterizedThreadStart(newSendmail.generateCaseEmail));
string[] paramsToPass = new String[] { entity.ProjectNumber, entity.CreatedBy, entity.TheProjectClientManagerFixed, entity.ProjectName };
caseemail.Start(paramsToPass);
How should I be doing this?
So in the end this code works, the errors were from problems access dataworkspaces from the other thread, which is obviously not allowed.
I will leave this here as an example of how to spin off a task into the background from lightswitch, leaving the interface responsive while lightswitch goes away and does something else.

How do I run function in vala asynchronously when a button is clicked

I am just starting out with Vala and have hit a hurdle
When I try and run a large function on a button press it locks the entire app up until it is finished
How would I put a something like the following into a thread or give it an asynchronous callback?
var btn = new Gtk.Button();
btn.label = "Run something massive!";
btn.clicked.connect (() => {
Process.spawn_command_line_sync("gksudo apt-get update",
out ls_stdout,
out ls_stderr,
out ls_status);
btn.set_sensitive (false);
});
In Gtk+, there is only one thread that processes GUI events. If you want to do a background process, you can either create a thread or split the task up and processes it in the main loop. I recommend the latter.
For launching a process, consider GLib.Process.spawn_async. To know when the process exits, you will have to install a handler using ChildWatch.
The example for ChildWatch is likely what you want.

how to make the silverlight page to wait for few seconds

I build silverlight application in that I am showing progress bar before the content is loaded and I need to pass the progress bar for few seconds and then I need to close..
I am using system.threading.thread.sleep(1000) but it makes the UI to freeze.
I need alternative in silverlight where in it should not freeze the UI and process should wait for some time...
By default everything is on the UI thread, so any time-consuming task will block the UI. To prevent this, push the execution to a background thread -- one way to do that is Task.Factory:
Task.Factory.StartNew( () => {
Thread.Sleep(1000);
});
Note that, if you then want to do anything with the UI (which I suppose you would), then you'll need to get back to the UI thread. (If a background thread tries to change the UI, the runtime will throw an exception.) Do that by using a Dispatcher:
Task.Factory.StartNew( () => {
// sleep on a background thread
Thread.Sleep(1000);
// when complete, return to the UI thread to prevent access violation
Application.Current.Dispatcher.BeginInvoke( () => {
// do UI stuff here
});
});

How to handle network thread calls and wait progress in J2me?

In my project I have created some network calls to the servlets in separate Thread where before that thread starts I show a spinner as wait progress. Until that network Thread finishes the waitprogress is displayed on to the screen and when I receive response from the server I have to explicitly call progress bar's dispose() method to dispose that progress bar. So, This is bit complicated whenever I make calls establishing GPRS connection while network strength goes down there I found sometimes it takes about 2-3 minutes to throw an IO Exception or receive response from server where I dispose waitprogress, show error message and proceed. I dont add any cancel command to waitprogress as network calls are made using separate thread so disposing waitprogress will allow user to make another call where the user is needed to wait until he gets response.
The above scenario is complicated because the user will not be waiting for this long to get response. There must be some way that whenever I call network Thread and show progress bar the user should be able to cancel all the operations including network thread, go back to previous state and make another call if there is no or poor connectivity.
Here, I am using Lwuit.
In NetworkManager class you can add this function and actived at from your class
only if lwuit is at open code in your application , you can add this function:
public void killAll() {
for (int i = 0; i < pending.size(); i++) {
((ConnectionRequest) pending.elementAt(i)).kill();
}
pending.removeAllElements();
for (int i = 0; i < networkThreads.length; i++) {
networkThreads[i].currentRequest.kill();
}
}
after or before this you need call dispose() method.

How to clean up AVCaptureSession in applicationDidEnterBackground?

I have an app that uses AVCaptureSession to process video. I like to write with zero memory leaks, and proper handling of all objects.
That's why this post - How to properly release an AVCaptureSession - was tremendously helpful - Since [session stopRunning] is asynchronous, you can't just stop the session and continue to release the holding object.
So that's solved. This is the code:
// Releases the object - used for late session cleanup
static void capture_cleanup(void* p)
{
CaptureScreenController* csc = (CaptureScreenController*)p;
[csc release]; // releases capture session if dealloc is called
}
// Stops the capture - this stops the capture, and upon stopping completion releases self.
- (void)stopCapture {
// Retain self, it will be released in capture_cleanup. This is to ensure cleanup is done properly,
// without the object being released in the middle of it.
[self retain];
// Stop the session
[session stopRunning];
// Add cleanup code when dispatch queue end
dispatch_queue_t queue = dispatch_queue_create("capture_screen", NULL);
dispatch_set_context(queue, self);
dispatch_set_finalizer_f(queue, capture_cleanup);
[dataOutput setSampleBufferDelegate: self queue: queue];
dispatch_release(queue);
}
Now I come to support app interruptions as a phone call, or pressing the home button. In case application enters background, I'd like to stop capturing, and pop my view controller.
I can't seem to do it at the applicationDidEnterBackground context. dealloc is never called, my object remains alive, and when I reopen the app the frames just start coming in automatically.
I tried using beginBackgroundTaskWithExpirationHandler but to no avail. It didn't change much.
Any suggestions?
Thanks!
I don't have an answer to your question.
But I also read the thread you mentioned and I'm trying to implement it.
I'm surprised you have this code in the stopCapture function:
// Add cleanup code when dispatch queue end
dispatch_queue_t queue = dispatch_queue_create("capture_screen", NULL);
dispatch_set_context(queue, self);
dispatch_set_finalizer_f(queue, capture_cleanup);
[dataOutput setSampleBufferDelegate: self queue: queue];
dispatch_release(queue);
I thought that code was required as part of the session initialization. Does this work for you?
Does your capture_cleanup function get called? mine isn't getting called and I'm trying to figure out why.

Resources