Web browser control WP8 using ram reduce on close view - windows-phone-8

i use in my application a webbrowser control.
i use the control for navigate to many site and when i close the view, the memory is not reduced.
Always remains on 50/60 MB.
it is possibile reduce memory?
i'm insert
protected override async void OnNavigatedFrom(NavigationEventArgs e)
{
await MyWebBrowser.ClearInternetCacheAsync();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
but not it works.

Related

Windows UWP, application crashing while suspending during async call

In my Windows store application, I have a await function, which sometimes takes couple of minutes to complete (will consult about performance in some other thread). Meanwhile if a user focuses out of the application, it crashes. When I checked event log, I got following error:
App was terminated because it took too long to suspend.
I am using Prism in the application. I have handled Application.Current.Suspending, with following code (which is always called):
protected void OnApplicationSuspending(object sender, SuspendingEventArgs e)
{
var defferal = e.SuspendingOperation.GetDeferral();
if (sessionStateService.SessionState.ContainsKey("plotId"))
{
sessionStateService.SessionState.Remove("plotId");
}
sessionStateService.SessionState.Add("plotId", Plot.Id);
if (sessionStateService.SessionState.ContainsKey("Page"))
{
sessionStateService.SessionState.Remove("Page");
}
sessionStateService.SessionState.Add("Page", "OperationRecording");
defferal.Complete();
}
I have also overridden OnNavigatingFrom function, for saving the navigation parameter (and it does nothing else).
public override void OnNavigatingFrom(NavigatingFromEventArgs e, Dictionary<string, object> viewModelState, bool suspending)
{
if (viewModelState.ContainsKey("plotId"))
{
viewModelState.Remove("plotId");
}
viewModelState.Add("plotId", Plot.Id);
base.OnNavigatingFrom(e, viewModelState, suspending);
}
I am not able to figure out how to fix this issue.
If you suspend your app you should complete it in 5 seconds.
Read Application.Suspending
Saving data prior to suspension is useful because the Suspending event
handler has only 5 seconds to complete its operation.
So, better save large amount of data due application working.
You can also read Guidelines for app suspend and resume
In UWP you can also make suspended time larger with help of Extended Execution

Can't Unlock Windows IOT Process after Debug

Trying to debug a Universal Windows app (MyTest) for Windows IOT using Local Machine. It starts the app but only displays the X screen, not my MainPage.xaml. OK, probably some bug I made. But I can't debug it and I can't unlock it. I try to put a breakpoint at App() constructor or OnLaunched and it never hits. If I Stop Debugging the X window stays up. Worse, if I kill the X window, using the window close (button in the top right), the app looks like it stops but the MyTest.exe remains locked, forever stopping me from trying to delete the exe, rebuild project, etc.
There is no MyTest app in the TaskManager (processes or details).
If I terminate ApplicationFrameHost process, the X screen will go away, but the MyTest.exe file remains locked as though the exe is still in use.
I've tried FileAssassin and it can't remove the lock.
The only thing that unlocks MyTest.exe is rebooting the machine...kind of a pain if you only get 1 debug run before rebooting the machine each time!
if you are using tasks you must terminate all.
example
BackgroundTaskDeferral _defferal;
public void Run(IBackgroundTaskInstance taskInstance)
{
_defferal = taskInstance.GetDeferral();
taskInstance.Canceled += TaskInstance_Canceled;
}
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
//a few reasons that you may be interested in.
switch (reason)
{
case BackgroundTaskCancellationReason.Abort:
//app unregistered background task (amoung other reasons).
break;
case BackgroundTaskCancellationReason.Terminating:
//system shutdown
break;
case BackgroundTaskCancellationReason.ConditionLoss:
break;
case BackgroundTaskCancellationReason.SystemPolicy:
break;
}
_defferal.Complete();
}
source: Windows 10 IOT Lifecycle (or: how to property terminate a background application)

ApplicationClose event

I'm developing Windows 10 universal app in C#/XAML.
I want to implement such a policy, that whenever user closes my app (and some other conditions are met, but its irrelevent here) an adverisment will display.
My question is how can I intercept and cancel/handle an event when application is being closed? This is easy when user decides to close the app by for example pressing a button that I'll define in XAML, but what if he presses Alt+F4? In Winforms this is easy as well:
private void Form1_Load(object sender, EventArgs e)
{
this.FormClosing += Form1_FormClosing;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
But how can I achieve similiar effect in in Windows 10 universal app?
I'm afraid there is no option to cancel the closing of the app or even delay it. The Suspending event is the only indication your app will receive prior to termination (if it happens). Check out the Application.Suspending event: https://msdn.microsoft.com/en-us/library/windows.ui.xaml.application.suspending.aspx
No, you can not achieve the similar effect in Windows 10 Universal App (and Windows 8.1 Store App), because in the modern app, the user have the full control of the app and the app can not stop the user closing a app.
If you have sth need to handle when user closing the application, as Lukkha stated, you can handle them in Application.Suspending, but there is a time limitation by default, all of the things should be done within 5s. If you want to have more than 5s, you need to request a ExtendedExecutionSession.
Using Extended Execution in Windows 10 Universal Apps

Handling back button on launch from secondary tile

How do I make the hardware back button return to the system's Start page when my app is launched from a secondary tile (i.e. deep linking)?
I'm using XAML and C#, by the way.
You can just clear the back stack if app is launched from a secondary tile.
Next press on back button will take user back to Start screen.
EDIT:
To clear the back stack:
If you're in page code behind, do
Frame.BackStack.Clear();
else do
var frame = Window.Current.Content as Frame;
frame.BackStack.Clear();
So, finally answering my own question months later...
The situation
Whenever my app is launched using a secondary tile, I have to make sure that the back stack is cleared by calling rootFrame.BackStack.Clear() on App.xaml.cs. That's necessary because if there is a suspended instance of my app in memory, this navigation from the secondary tile is added to the top of whatever back stack that suspended instance had. This is a problem because it makes a press of the back button return to the previous page on the stack instead of the Start screen, which is the appropriate behavior for secondary tile launches.
The problem
If the user "cold launches" the app using a secondary tile, whenever s/he leaves it Windows will suspend that session of the app with a clear back stack. That means that new launches from the primary tile will restore that page that was called from the secondary tile, and pressing the back button will suspend the app again instead of going to the app's main page.
The solution
It's actually documented by Microsoft, but only textually (https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn639128.aspx):
Ensure proper Back button behavior when your app supports multiple launch points
Consider creating new instances of navigation journals for launch points such as primary and secondary tiles, file and URI Associations. Save the activation parameters each time the app is launched and compare when the app is being re-launched. If the app is being re-launched with different parameters, consider creating a new navigation history. Do this by creating a new Frame. This will allow the user to quickly navigate back to the launch point when the hardware Back key button is pressed. To maintain a small memory footprint, the Navigation history for launch points other than the Primary tile doesn’t need to be saved when the app is suspended.
In practice, for me, that meant writing the last received launch argument to a text file in my app's storage and reading it back on the beginning of the OnLaunched method in App.xaml.cs. Then I compare the read value to the current launch arguments. If they are different, I simply assign null to the rootFrame variable, so that a new "navigation journal" is created:
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
...
Frame rootFrame = Window.Current.Content as Frame;
var lastArgument = await ReadLastArgument();
if (!string.Equals(lastArgument,currentArgument))
rootFrame = null;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active.
if (rootFrame == null){
...
}
...
if (!String.IsNullOrEmpty(e.Arguments))
{
WriteLastArgument(e.Arguments);
//Navigate to the page...
...
rootFrame.BackStack.Clear();
}
private async Task<string> ReadLastArgument()
{
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
StorageFile file = await folder.GetFileAsync("lastArgument.txt");
var argument = await Windows.Storage.FileIO.ReadTextAsync(file);
return argument;
}
catch (System.IO.FileNotFoundException)
{
return "";
}
}
private async void WriteLastArgument(string argument)
{
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync("lastArgument.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, argument);
}
}

how to load high resolution image windows phone taskagent? [out of memory]

As we know, it is only 11.5MB memory that can be used in a Windows Phone 8 task agent. I was trying to make dynamic lock screen image in the background task agent. When I get the 480*800 image, it works fine but when I change it to 768*1280 I the exception:
Out of memory
1 pixel cast 4 K
so
(480*800*4)/1024/1024=1.46M
(768*1280*4)/1024/1024 = 3.75M
When I tried to convert a byte[] to a BitmapImage:
public BitmapImage ConvertDownloadStringToStream(byte[] downloadImageBytes)
{
if (!(downloadImageBytes.Length > 0))
return null;
RationImageInfo currentRationInfor = GetBitmapImageWidthByDeveiceRatio();
BitmapImage convertBitmapImage = new BitmapImage() { DecodePixelWidth =768, DecodePixelHeight = 1280};
using (MemoryStream imageStream = new MemoryStream(downloadImageBytes))
{
convertBitmapImage.SetSource(imageStream);//out of memory
}
return convertBitmapImage;
}
I get the out of memory exception at SetSource() method. Does anyone have suggestions about this?
I'm guessing the memory adds up.
Try saving it to a file, free the variable/resource, than load it from the file using the constructor parameter.
just try some many times i has been fix this problem.
as you see it was only have 11M memory can be use in windows phone taskagent. i was tring to make dynamic lock screen background. my soluction is download image from sever side and save to local display it.
why got out of memory Exception?
download image Byte[]=>Write to memory=>build writeableBitmap with 768*1280.
same image memory just cast three time .
so how to fix it ?
when you download your image from server side. you should be save to local isolate storage immediately and clear memory useage about the image byte[]. just set the image url to lockscreen . got be work.
download image Byte[]=>Save To local =>clear image byte memory.
everything is fine.