Some small tweaks to improve the memory alloc

pull/470/head
tidusjar 9 years ago
parent 5d18877b49
commit 7f6c70d7b2

@ -1,130 +1,133 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: MemoryCacheProvider.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Linq;
using System.Runtime.Caching;
using System.Threading.Tasks;
namespace PlexRequests.Helpers
{
public class MemoryCacheProvider : ICacheProvider
{
private ObjectCache Cache => MemoryCache.Default;
/// <summary>
/// Gets the item from the cache, if the item is not present
/// then we will get that item and store it in the cache.
/// </summary>
/// <typeparam name="T">Type to store in the cache.</typeparam>
/// <param name="key">The key.</param>
/// <param name="itemCallback">The item callback. This will be called if the item is not present in the cache.
/// </param>
/// <param name="cacheTime">The amount of time we want to cache the object.</param>
/// <returns>A copy of the cached object.</returns>
/// <remarks>If the <c><![CDATA[Func<T>]]> itemCallback</c> is null and the item is not in the cache it will throw a <see cref="NullReferenceException"/>.
/// <para>If you do not want to change the object in the cache (since it's a copy returned and not a reference) you will need to <see cref="Remove"/>
/// the cached item and then <see cref="Set"/> it, or just call this method.</para></remarks>
public T GetOrSet<T>(string key, Func<T> itemCallback, int cacheTime = 20) where T : class
{
var item = Get<T>(key);
if (item == null)
{
item = itemCallback();
if (item != null)
{
Set(key, item, cacheTime);
}
}
// Return a copy, not the stored cache reference
// The cached object will not change
// If we
return item.CloneJson();
}
public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> itemCallback, int cacheTime = 20) where T : class
{
var item = Get<T>(key);
if (item == null)
{
item = await itemCallback();
if (item != null)
{
Set(key, item, cacheTime);
}
}
// Return a copy, not the stored cache reference
// The cached object will not change
return item.CloneJson();
}
/// <summary>
/// Gets the specified item from the cache.
/// </summary>
/// <typeparam name="T">Type to get from the cache</typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public T Get<T>(string key) where T : class
{
lock (key)
return Cache.Get(key) as T;
}
/// <summary>
/// Set/Store the specified object in the cache
/// </summary>
/// <param name="key">The key.</param>
/// <param name="data">The object we want to store.</param>
/// <param name="cacheTime">The amount of time we want to cache the object.</param>
public void Set(string key, object data, int cacheTime = 20)
{
var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime) };
lock (key)
{
Cache.Remove(key);
Cache.Add(new CacheItem(key, data), policy);
}
}
/// <summary>
/// Removes the specified object from the cache.
/// </summary>
/// <param name="key">The key.</param>
public void Remove(string key)
{
var keys = Cache.Where(x => x.Key.Contains(key));
foreach (var k in keys)
{
lock (key)
{
Cache.Remove(k.Key);
}
}
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: MemoryCacheProvider.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Linq;
using System.Runtime.Caching;
using System.Threading.Tasks;
namespace PlexRequests.Helpers
{
public class MemoryCacheProvider : ICacheProvider
{
private ObjectCache Cache => MemoryCache.Default;
private readonly object _lock = new object();
/// <summary>
/// Gets the item from the cache, if the item is not present
/// then we will get that item and store it in the cache.
/// </summary>
/// <typeparam name="T">Type to store in the cache.</typeparam>
/// <param name="key">The key.</param>
/// <param name="itemCallback">The item callback. This will be called if the item is not present in the cache.
/// </param>
/// <param name="cacheTime">The amount of time we want to cache the object.</param>
/// <returns>A copy of the cached object.</returns>
/// <remarks>If the <c><![CDATA[Func<T>]]> itemCallback</c> is null and the item is not in the cache it will throw a <see cref="NullReferenceException"/>.
/// <para>If you do not want to change the object in the cache (since it's a copy returned and not a reference) you will need to <see cref="Remove"/>
/// the cached item and then <see cref="Set"/> it, or just call this method.</para></remarks>
public T GetOrSet<T>(string key, Func<T> itemCallback, int cacheTime = 20) where T : class
{
var item = Get<T>(key);
if (item == null)
{
item = itemCallback();
if (item != null)
{
Set(key, item, cacheTime);
}
}
// Return a copy, not the stored cache reference
// The cached object will not change
// If we
return item.CloneJson();
}
public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> itemCallback, int cacheTime = 20) where T : class
{
var item = Get<T>(key);
if (item == null)
{
item = await itemCallback();
if (item != null)
{
Set(key, item, cacheTime);
}
}
// Return a copy, not the stored cache reference
// The cached object will not change
return item.CloneJson();
}
/// <summary>
/// Gets the specified item from the cache.
/// </summary>
/// <typeparam name="T">Type to get from the cache</typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public T Get<T>(string key) where T : class
{
lock (_lock)
{
return Cache.Get(key) as T;
}
}
/// <summary>
/// Set/Store the specified object in the cache
/// </summary>
/// <param name="key">The key.</param>
/// <param name="data">The object we want to store.</param>
/// <param name="cacheTime">The amount of time we want to cache the object.</param>
public void Set(string key, object data, int cacheTime = 20)
{
var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime) };
lock (_lock)
{
Cache.Remove(key);
Cache.Add(new CacheItem(key, data), policy);
}
}
/// <summary>
/// Removes the specified object from the cache.
/// </summary>
/// <param name="key">The key.</param>
public void Remove(string key)
{
var keys = Cache.Where(x => x.Key.Contains(key));
foreach (var k in keys)
{
lock (_lock)
{
Cache.Remove(k.Key);
}
}
}
}
}

@ -43,7 +43,7 @@ namespace PlexRequests.Services.Interfaces
/// Gets the episode's stored in the cache.
/// </summary>
/// <returns></returns>
IEnumerable<PlexEpisodeModel> GetEpisodeCache();
HashSet<PlexEpisodeModel> GetEpisodeCache();
/// <summary>
/// Gets the episode's stored in the cache and then filters on the TheTvDBId.
/// </summary>

@ -241,7 +241,7 @@ namespace PlexRequests.Services.Jobs
public bool IsEpisodeAvailable(string theTvDbId, int season, int episode)
{
var episodes = Cache.Get<List<PlexEpisodeModel>>(CacheKeys.PlexEpisodes);
var episodes = Cache.Get<HashSet<PlexEpisodeModel>>(CacheKeys.PlexEpisodes);
if (episodes == null)
{
Log.Info("Episode cache info is not available. tvdbid: {0}, season: {1}, episode: {2}",theTvDbId, season, episode);
@ -261,13 +261,13 @@ namespace PlexRequests.Services.Jobs
/// Gets the episode's stored in the cache.
/// </summary>
/// <returns></returns>
public IEnumerable<PlexEpisodeModel> GetEpisodeCache()
public HashSet<PlexEpisodeModel> GetEpisodeCache()
{
var episodes = Cache.Get<List<PlexEpisodeModel>>(CacheKeys.PlexEpisodes);
var episodes = Cache.Get<HashSet<PlexEpisodeModel>>(CacheKeys.PlexEpisodes);
if (episodes == null)
{
Log.Info("Episode cache info is not available.");
return new List<PlexEpisodeModel>();
return new HashSet<PlexEpisodeModel>();
}
return episodes;
}

@ -65,6 +65,7 @@ namespace PlexRequests.Services.Jobs
public void CacheEpisodes()
{
var results = new PlexSearch();
var videoHashset = new HashSet<Video>();
var settings = Plex.GetSettings();
if (string.IsNullOrEmpty(settings.PlexAuthToken))
{
@ -85,32 +86,26 @@ namespace PlexRequests.Services.Jobs
currentPosition += ResultCount;
while (currentPosition < totalSize)
{
results.Video.AddRange(PlexApi.GetAllEpisodes(settings.PlexAuthToken, settings.FullUri, tvSectionId, currentPosition, ResultCount).Video);
videoHashset.UnionWith(PlexApi.GetAllEpisodes(settings.PlexAuthToken, settings.FullUri, tvSectionId, currentPosition, ResultCount).Video
.Where(x => x.Type.Equals(PlexType, StringComparison.InvariantCultureIgnoreCase)));
currentPosition += ResultCount;
}
var filteredList = results.Video.Where(x => x.Type.Equals(PlexType, StringComparison.InvariantCultureIgnoreCase));
var episodesModel = new List<PlexEpisodeModel>();
var metadataList = new List<PlexEpisodeMetadata>();
var episodesModel = new HashSet<PlexEpisodeModel>();
foreach (var video in filteredList)
foreach (var video in videoHashset)
{
var ratingKey = video.RatingKey;
var metadata = PlexApi.GetEpisodeMetaData(settings.PlexAuthToken, settings.FullUri, ratingKey);
metadataList.Add(metadata);
}
foreach (var m in metadataList)
{
foreach (var video in m.Video)
foreach (var metadataVideo in metadata.Video)
{
episodesModel.Add(new PlexEpisodeModel
{
RatingKey = video.RatingKey,
EpisodeTitle = video.Title,
Guid = video.Guid,
ShowTitle = video.GrandparentTitle
RatingKey = metadataVideo.RatingKey,
EpisodeTitle = metadataVideo.Title,
Guid = metadataVideo.Guid,
ShowTitle = metadataVideo.GrandparentTitle
});
}
}

@ -130,7 +130,6 @@
generateNotify(response.message, "success");
$('#spinner').attr("class", "fa fa-check");
$('#authToken').val(response.authToken);
} else {
generateNotify(response.message, "warning");
$('#spinner').attr("class", "fa fa-times");

Loading…
Cancel
Save