ExtendedExecutionSession in Windows 10 Universal app - windows-10-universal

I have task that is already running when the app is suspending. I need to request ExtendedExecutionSession to let the task finish executing.
I after obtaining deferral request ExtendedExecutionSession in app OnSuspending handler and the extended execution is granted.
When do I need to call deferral.Complete()? I found that if call in the end of OnSuspending after requesting extendedexcdution that execution does not work, the app stays in tombstoned state.
private static async void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// request extended execution to let already running task to finish
await RequestExtendedSession();
// if call this the app is tombstoned and no code is executing when the app is suspended
deferral.Complete();
}

Related

ConfigureAwait , UI, await async

I have a small project - WinForms
On .net frameWork - just a small test :
private void button9_Click(object sender, EventArgs e)
{
string text = GetTitleAsync().Result;
button9.Text = text;
}
private async Task<string> GetTitleAsync()
{
await Task.Delay(3000);
return "Hello!";
}
As I ran the application ,
Clicking the button: "button9" - caused a dead lock,
(since the thread was hung on the ".result" )
Writing GetTitleAsync() this way:
private async Task<string> GetTitleAsync()
{
await Task.Delay(3000).ConfigureAwait(false);
return "Hello!";
}
solved the deadlock - and the application ran ok.
But I don't understand how ?
I would have expected, that using ".ConfigureAwait(false)" would cause a
situation in which :
"button9.Text = text;" is executed on a different thread than
the one, on which the UI was created,
and an excpetion would be throwed !
but it works excellent !
how??
I would have expected, that using ".ConfigureAwait(false)" would cause a situation in which "button9.Text = text;" is executed on a different thread than the one, on which the UI was created, and an excpetion would be throwed ! but it works excellent ! how??
I recommend reading my async/await intro; I try to include everything you need to know about async/await and their contexts, without getting into too much detail for an intro.
Specifically, there are two points from that post that are worth noting:
Every async method begins executing synchronously, on the calling thread.
await captures a context unless you use ConfigureAwait(false).
So, walking through this code:
private void button9_Click(object sender, EventArgs e)
{
string text = GetTitleAsync().Result;
button9.Text = text;
}
private async Task<string> GetTitleAsync()
{
await Task.Delay(3000).ConfigureAwait(false);
return "Hello!";
}
This is what happens, in order, with special attention paid to which thread runs which code:
button9_Click calls GetTitleAsync() on the UI thread.
GetTitleAsync() calls Task.Delay(3000) and gets back a task that will complete in 3 seconds.
GetTitleAsync() calls ConfigureAwait(false) and gets back a configured awaiter that will not resume on the current (UI) context.
GetTitleAsync() uses await to asynchronously wait for the task to complete. This await will not resume on the current (UI) context because the await has been configured not to.
The await examines the task and sees it is not complete, so it returns an incomplete Task<string> to its caller.
button9_Click calls .Result on that task. This blocks the UI thread until that task completes (i.e., GetTitleAsync() is finished executing).
Three seconds later, the task returned from Task.Delay(3000) completes.
GetTitleAsync() resumes executing after its await. Since this was a configured await, it continues executing on a thread pool thread.
GetTitleAsync() returns "Hello!". This is done on a thread pool thread.
By returning a value, GetTitleAsync() is now complete, and the Task<string> that it returned earlier is now completed with a result value. This completion also happens on a thread pool thread.
Since the task is now complete, the UI thread is no longer blocked, and it continues executing button9_Click.
button9_Click executes button9.Text = text; on the UI thread.

multiple asynchronous tasks finish one after another and allow user to do other work till get finished all tasks

my application is WPf and we have data service.
I would like to call async data service task to do some work and return once it done. while async task is doing his job my client can do other work.
but when i would like to call 10 same task by for loop and i want to do each task one after the other task but not parallel. Also my client can continue other work till all 10 task get finished.
if i use task[i].wait() will not allow my client to continue other work. client cannot do anything else till each task get done.
Blocking calls like .Wait() and .Result wont let the UI continue
Use async/await, like for example in a button click event
public async void btn_Clicked(object sender, EventArgs args) {
for (int i = 0; i < someParameter; i++) {
await importExportServiceClient.ClientEntryImportExportAsync(ImpExpobj, start, end, chunk);//for running task to finish
}
}
each task will be awaited in turn without blocking the client. Allowing the client to continue other work till all tasks are completed.
Reference Async/Await - Best Practices in Asynchronous Programming

Win App using Background worker process running on Terminal Server goes Non responsive

There is a Win app tool(C#) running at terminal server which is used to download mails, process the attachment in it and update its UI. Downloading and processing of mail attachments is done using the Background Worker process which also responsible for updating the UI with mails and attachments total and processed count at that instance. There is a timer which ticks to re-initializes the same background worker process after specified duration and look for new mails.
All works fine till the time I am logged in RDC, but when I lock the system (Window key+L) or switch users and comeback to regain the same session the tool is stuck/non responsive, it happens even if I lock and unlock the system instantaneously. I used another process monitoring tool which initially showed child threads getting created and exited periodically but after it is stuck no activity is shown.
I have no clue why is it happening, is window messing is stopped or UI Controls handle are lost or or or....
Following are the chunks of code I am using:
private void tmrScheduler_Tick(object sender, EventArgs e)
{
Application.DoEvents();
if (bgwMailParser == null || (!bgwMailParser.IsBusy && !objfeMailImportNParse.Is_Parsing))
{
bgwMailParser = new BackgroundWorker();
bgwMailParser.DoWork += new DoWorkEventHandler(objfeMailImportNParse.opLoadCommonData);
bgwMailParser.DoWork += new DoWorkEventHandler(objfeMailImportNParse.StartMailImport);
if (HireCraft.Properties.Settings.Default.Close_App_After_Parsing)
bgwMailParser.RunWorkerCompleted += new RunWorkerCompletedEventHandler(opCloseApplication);
bgwMailParser.RunWorkerCompleted += new RunWorkerCompletedEventHandler(opDisposeWorker);
bgwMailParser.RunWorkerAsync();
}
Application.DoEvents();
}
below method handles the events raised by bgWorker process
private delegate void Del_updateParsedCounter(Int64 del_MailCount, Int64 del_AttchCount);
private void UpdateParsedCounter(Int64 MailCount, Int64 AttchCount)
{
try
{
if (lblMailParsedCount.InvokeRequired)
{
Del_updateParsedCounter objUpdateParsedCounter = new Del_updateParsedCounter(UpdateParsedCounter);
this.Invoke(objUpdateParsedCounter, new object[] { MailCount, AttchCount });
}
else
{
lblMailParsedCount.Text = MailCount.ToString();
lblAttchSavedCount.Text = AttchCount.ToString();
}
}
catch (Exception ex)
{
Debug.Assert(false, ex.Message, ex.StackTrace);
}
}
I identified solution to issue but forgot that I raised a question here which wasn't answered.
Well issue was the background worker thread declaring a UIControl deep down somewhere in the code.
When a thread creates a UIControl it also registers itself with SystemEvents.UserPreferenceChanged event which notifies color, theme, screen size changes, system lock/unlock etc. and to respond to which parent thread requires a message pump lacking in background worker thread, the event invoke waits for a (never coming) response causing the application to hang or act non-responsive.
http://support.microsoft.com/kb/943139 link to Microsoft support explains the same.

MessageBox.Show early in App startup causes app to terminate

As part of my App's startup procedure, it checks data integrity, and if it finds a problem it pops up a message to the user telling them that it might take a while to repair things.
I'm showing the message using MessageBox.Show. Because the data check is done from a worker thread, I'm switching over to the UI thread to make that call, and then setting a ManualResetEvent to tell the worker thread when the user has acknowledged the message.
I kick off the data check/load very early in the app's lifecycle from the constructor in the main Application class, by spinning off a worker thread (using the ThreadPool).
When I run with the debugger, and the message is displayed, the app just waits for input. When I run without the debugger, the app terminates after displaying the dialog for 10 seconds.
That 10 seconds is a big clue - it tells me that the OS thinks the app took too long to initialize (the OS kills apps that take too long to start up).
I think that my MessageBox.Show is blocking the UI thread before the App.RootFrameNavigating has a chance to be invoked.
My questions:
Does my diagnosis sound right?
I'd prefer to kick off my data load early, because it is almost entirely IO, except for this Message Box, and the sooner I can get my Model loaded, the better, but do you normally delay your data load until later in the app lifecycle?
Any other ideas/suggestions? I can't guarantee which page will be the start page, because the app could be resuming to any page. I'm also thinking of having the MessageBox.Show delay itself until the app has initialized, perhaps polling away for a flag set by App.RootFrameNavigating - does that make sense?
I think your problem is a result of kicking off the worker thread in the Application constructor. You should use the appropriate life-cycle event, in this case: PhoneApplicationService.Activated Event
So, the solution I've come up with is to still kick off the data load in a worker-thread from the Application's constructor, but in my PhoneService's class ShowDialog method that I invoke to invoke MessageBox.Show, I check to see if the initial navigation has occurred:
private readonly ManualResetEvent _appInitialized = new ManualResetEvent(false);
public void AppInitialized()
{
_appInitialized.Set();
}
public void ShowDialog(string caption, string text, Action<MessageBoxResult> callback, MessageBoxButton button = MessageBoxButton.OKCancel)
{
_appInitialized.WaitOne();
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
var result = MessageBox.Show(text, caption, button);
if (callback != null)
{
callback(result);
}
});
}
Then in my Application class:
private bool _firstNavigate = true;
private void RootFrameNavigating(object sender, NavigatingCancelEventArgs e)
{
if (_firstNavigate)
{
_firstNavigate = false;
var navigationService = (NavigationService) sender;
navigationService.Navigated += NavigationServiceNavigated;
}
....
private void NavigationServiceNavigated(object sender, NavigationEventArgs e)
{
var navigationService = (NavigationService)sender;
navigationService.Navigated -= NavigationServiceNavigated;
PhoneServices.Current.AppInitialized();
}
Anyone see any issues with this approach? Anyone come up with a better way?

What happens if an application calls more than 10 asynchronous URL Fetch on Google App Engine?

Reading the Google App Engine documentation on asynchronous URL Fetch:
The app can have up to 10 simultaneous
asynchronous URL Fetch calls
What happens if an application calls more than 10 async fetch at a time?
Does Google App Engine raise an exception or simply queue the remain calls waiting to serve them?
Umm, Swizzec is incorrect. Easy enough to test:
rpc = []
for i in range(1,20):
rpc.append(urlfetch.createrpc())
urlfetch.make_fetch_call(rpc[-1],"http://stackoverflow.com/questions/3639855/what-happens-if-i-call-more-than-10-asynchronous-url-fetch")
for r in rpc:
response = r.get_result().status_code
This does not return any exceptions. In fact, this works just fine! Note that your results may vary for non-billable applications.
What Swizec is reporting is a different problem, related to maximum simultaneous connections INTO your application. For billable apps there is no practical limit here btw, it just scales out (subject to the 1000ms rule).
GAE has no way of knowing that your request handler will issue a blocking URL fetch, so the connection 500's he is seeing are not related to what his app is actually doing (that's an oversimplification btw, if your average request response time is > 1000ms your likelyhood of 500's increases).
This is an old question, but I believe the accepted answer is incorrect or outdated and may confuse people. It's been a couple of months that I actually tested this, but in my experience Swizec is quite right that GAE will not queue but rather fail most asynchronous URL fetches exceeding the limit of around 10 simultaneous ones per request.
See https://developers.google.com/appengine/docs/python/urlfetch/#Python_Making_requests and https://groups.google.com/forum/#!topic/google-appengine/EoYTmnDvg8U for a description of the limit.
David Underhill has come up with a URL Fetch Manager for Python, which queues asynchronous URL fetches that exceed the limit in application code.
I have implemented something similar for Java, which synchronously blocks (due to the lack of a callback function or ListenableFutures) additional requests:
/**
* A URLFetchService wrapper that ensures that only 10 simultaneous asynchronous fetch requests are scheduled. If the
* limit is reached, the fetchAsync operations will block until another request completes.
*/
public class BlockingURLFetchService implements URLFetchService {
private final static int MAX_SIMULTANEOUS_ASYNC_REQUESTS = 10;
private final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
private final Queue<Future<HTTPResponse>> activeFetches = new LinkedList<>();
#Override
public HTTPResponse fetch(URL url) throws IOException {
return urlFetchService.fetch(url);
}
#Override
public HTTPResponse fetch(HTTPRequest request) throws IOException {
return urlFetchService.fetch(request);
}
#Override
public Future<HTTPResponse> fetchAsync(URL url) {
block();
Future<HTTPResponse> future = urlFetchService.fetchAsync(url);
activeFetches.add(future);
return future;
}
#Override
public Future<HTTPResponse> fetchAsync(HTTPRequest request) {
block();
Future<HTTPResponse> future = urlFetchService.fetchAsync(request);
activeFetches.add(future);
return future;
}
private void block() {
while (activeFetches.size() >= MAX_SIMULTANEOUS_ASYNC_REQUESTS) {
// Max. simultaneous async requests reached; wait for one to complete
Iterator<Future<HTTPResponse>> it = activeFetches.iterator();
while (it.hasNext()) {
if (it.next().isDone()) {
it.remove();
break;
}
}
}
}
}
500 errors start happening. Silently.
You only find out about these when you look at your log under all requests (don't get listed as errors). It simply says "The request was aborted because you reached your simultaneous requests limit".
So when you're making lots of asynchronous calls, make sure you can handle some of them spazzing out.
See if this answers your question:
http://groups.google.com/group/google-appengine/browse_thread/thread/1286139a70ef83c5?fwc=1

Resources