2017-11-20 8 views
0

メモリの問題が深刻化しています。ときどき数分後に、メモリ不足例外のためにアプリがクラッシュします。私はSQLサーバーデータベースからイメージを取得し、別のクラスのバイトから変換します。多くの画像がメモリを吸い取ってメモリの例外が出ていますか?

私のXAMLビュー:背後

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      x:Class="TestProject.Views.DetailViews.JsonDesertPage" 
      xmlns:local ="clr-namespace:TestProject.Data"> 
    <ContentPage.Resources> 
     <ResourceDictionary> 
      <local:ByteArrayToImageConverter x:Key="severityTypeImageConvertertwo"/> 
     </ResourceDictionary> 
    </ContentPage.Resources> 
    <ListView x:Name="listviewConactstwo" RowHeight="100" HorizontalOptions="FillAndExpand" HasUnevenRows="True" ItemSelected="listviewContacts_ItemSelected"> 
     <ActivityIndicator x:Name="ProgressLoadertwo" IsRunning="True"/> 
     <ListView.ItemTemplate > 
      <DataTemplate> 
       <ViewCell> 
        <StackLayout Orientation="Vertical" Padding="5"> 
         <StackLayout Orientation="Horizontal" BackgroundColor="Ivory" Opacity="0.9"> 
          <Image Source="{Binding Image,Converter={StaticResource severityTypeImageConvertertwo}}" HeightRequest="120" WidthRequest="120"/> 
          <StackLayout Orientation="Vertical"> 
           <Label Text="{Binding Name}" FontSize="Medium" TextColor="Gray" FontAttributes="Bold"/> 
           <BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" HorizontalOptions="FillAndExpand" /> 
           <Label Text="{Binding Description}" FontSize="Micro" TextColor="Gray" FontAttributes="Bold"/> 
           <StackLayout Orientation="Horizontal" VerticalOptions="Start" HorizontalOptions="Start"> 
            <Label Text="$" FontSize="Micro" VerticalOptions="Start" HorizontalOptions="Start" TextColor="Gray" FontAttributes="Bold"/> 
            <Label Text="{Binding Price}" FontSize="Micro" TextColor="Gray" FontAttributes="Bold"/> 
           </StackLayout> 
          </StackLayout> 
          <Image Source="arrowtwo.png" BackgroundColor="Transparent" WidthRequest="25" Margin="0,10,10,0"/> 
         </StackLayout>       
        </StackLayout>      
       </ViewCell>     
      </DataTemplate>    
     </ListView.ItemTemplate>   
    </ListView> 
</ContentPage> 

は私のコード:

using Newtonsoft.Json; 
using Plugin.Connectivity; 
using System; 
using System.IO; 
using System.Net.Http; 
using TestProject.Data; 
using TestProject.Models; 
using Xamarin.Forms; 

namespace TestProject.Views.DetailViews 
{ 
    public partial class JsonDesertPage : ContentPage 
    { 
     public JsonDesertPage() 
     { 
      InitializeComponent(); 

      this.BackgroundImage = "background.png"; 
      this.Title = "Soup Menu"; 
      GetJSON(); 
      // CrossConnectivity.Current.ConnectivityChanged += Current_ConnectivityChanged; 
     } 


     protected async override void OnAppearing() 
     { 
      base.OnAppearing(); 

      if (!CrossConnectivity.Current.IsConnected) 
      { 
       await DisplayAlert("fail", "No Internet Connection.Offline Menu Activated", "Ok"); 
       await Navigation.PushAsync(new MainTabbed()); 
      } 
      else 
      { 
       // await DisplayAlert("sucess", " Network Is Available.", "Ok"); 
       GetJSON(); 
      } 
     } 

     public async void GetJSON() 
     {     
      var client = new HttpClient(); 
      // var response = await client.GetAsync("http://192.168.43.226/GetContactsDesert.php"); 
      var response = await client.GetAsync(Constants.BaseUrlpos + "GetContactsDesert.php");  

      string contactsJson = response.Content.ReadAsStringAsync().Result; 
      ContectList ObjContactList = new ContectList(); 

      if (response.IsSuccessStatusCode) 
      {      
       ObjContactList = JsonConvert.DeserializeObject<ContectList>(contactsJson); 
       listviewConactstwo.ItemsSource = ObjContactList.contacts; 
      } 

      else 
      { 
       var textReader = new JsonTextReader(new StringReader(contactsJson)); 
       dynamic responseJson = new JsonSerializer().Deserialize(textReader); 
       contactsJson = "Deserialized JSON error message: " + responseJson.Message; 
       await DisplayAlert("fail", "no Network Is Available.", "Ok"); 
      } 

      ProgressLoadertwo.IsVisible = false;    

     } 

     private void listviewContacts_ItemSelected(object sender, SelectedItemChangedEventArgs e) 
     { 
      var itemSelectedData = e.SelectedItem as Contactone; 
      Navigation.PushAsync(new JsonDetailsPage(itemSelectedData.ID, itemSelectedData.Image, itemSelectedData.Name, itemSelectedData.Code, itemSelectedData.Description, itemSelectedData.Price,itemSelectedData.isservicecharge, itemSelectedData.CostPrice)); 

     } 
    } 
} 

は、これは私が使用しているページのいずれかである:

using System; 
using System.Collections.Generic; 
using System.Globalization; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Xamarin.Forms; 

namespace TestProject.Data 
{ 
    public class ByteArrayToImageConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      ImageSource retSource = null; 
      if (value != null) 
      { 
       byte[] imageAsBytes = (byte[])value; 
       // byte[] decodedByteArray = System.Convert.FromBase64String(Encoding.UTF8.GetString(imageAsBytes, 0, imageAsBytes.Length)); 
       // var stream = new MemoryStream(decodedByteArray); 
       retSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes)); 
      } 
      return retSource; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      //return null; 
      throw new NotImplementedException(); 
     } 

    } 
} 

私は私ができるプロファイルを実行したとき私がページの中を進むにつれ、バイバイが育っているのを見てください。私はFFimageloadingオプションを試して、バイト配列イメージコンバータをサポートしていないようです。

メモリの問題を解決するにはどうすればよいですか?

答えて

0

いくつか発見されました。完全な実行がなければ、私はどちらがあなたの頭痛だと判断できませんが...

HttpClientをシングルトンとして使用してください。私は、Xamアーチでシングルトン使用がXamに最適であることを確認しました。

ID可能なオブジェクトに注意してください。

次のコードは、HttpResponseメソッドを返します。 HttpResponseMessageはIDisposableです。それを「使用する」で包みます。

StringReaderはIDisposableであるTextReaderを継承します。ラップ "を使用して"。

動的タイプは不定です。それをラップするのもベストです。詳細はDo you need to dispose of objects and set them to null?を参照してください。 HttpClientをへ

PNPガイド - https://github.com/mspnp/performance-optimization/blob/465514674354c8f833c73882f7405ac22c4fd437/ImproperInstantiation/docs/ImproperInstantiation.md

PNP良い/悪いのHttpClientサンプル - https://github.com/mspnp/performance-optimization/tree/465514674354c8f833c73882f7405ac22c4fd437/ImproperInstantiation

あなたは間違っているのHttpClientを使用していて、それはあなたのソフトウェアを不安定にされて - これは場合に役立ちます

http://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/を参照してください。

private HttpClient m_httpClient = new HttpClient(); 
    private HttpClient MyHttpClient 
    { 
     get 
     { 
      if (m_httpClient==null) 
      { 
       m_httpClient = new HttpClient(); 
      } 
      return m_httpClient; 
     } 
    } 
    public async void GetJSON() 
    { 
     // var client = new HttpClient(); 
     var client = MyHttpClient; 

     // var response = await client.GetAsync("http://192.168.43.226/GetContactsDesert.php"); 
     // var response = await client.GetAsync(Constants.BaseUrlpos + "GetContactsDesert.php"); 
     string contactsJson = string.Empty; 
     using (HttpResponseMessage response = await client.GetAsync(Constants.BaseUrlpos + "GetContactsDesert.php")) 
     { 
      contactsJson = response.Content.ReadAsStringAsync().Result; 
     } 
     ContectList ObjContactList = new ContectList(); 

     if (response.IsSuccessStatusCode) 
     { 
      ObjContactList = JsonConvert.DeserializeObject<ContectList>(contactsJson); 
      listviewConactstwo.ItemsSource = ObjContactList.contacts; 
     } 

     else 
     { 
      using (var textReader = new JsonTextReader(new StringReader(contactsJson))) 
      { 
       using (dynamic responseJson = new JsonSerializer().Deserialize(textReader)) 
       { 
        contactsJson = "Deserialized JSON error message: " + responseJson.Message; 
       } 
       await DisplayAlert("fail", "no Network Is Available.", "Ok"); 
      } 
     } 

     ProgressLoadertwo.IsVisible = false; 
    } 
+0

答えあちこちにどうもありがとう、しかし、エラーがあったが、「(response.IsSuccessStatusCode)の場合」で示したものであり、私は可能それを修正しようとしましたが、ありません、私は場合はあなたにxamarinプロファイラ画像を表示することができますあなたは、画像がリストビューに読み込まれるときのスタックの割合を気に入っています。限り、私は理由は、読み込まれた画像のスタックの増加が処分されていない理解しています。次のページに移動するときにlistviewイメージを処理する方法があると、プリロードされたイメージを保持するのを助けるかもしれませんが、問題はどうしたらいいのですか? – pan

+0

簡単な再生を投稿する私はGitHubに走ることができ、私は見ていきます。 –

+0

私は終了するgithubに新しいので、私は私のプロジェクトファイルをアップロードしている場合は、私はgithubのリンクを変更することを知っていることができない場合はhttps://github.com/wpanduka/panPosSystem – pan

関連する問題