How do I properly use async and await in this code?
My Windows Form application freezes when deserializing "all episodes" from a local XML-file. I want to solve this problem by implementing asynchronous programming but unfortunately I do not succeed with the implementation (I am a beginner and it's the first time I use await and async).
Working (but freezing) synchronous execution:
public class EpisodeRepository : IEpisodeRepository<Episode>
{
SerializerForXml dataManager;
List<Episode> listOfEpisodes;
public EpisodeRepository()
{
dataManager = new SerializerForXml();
listOfEpisodes = new List<Episode>();
listOfEpisodes = GetAll();
}
public List<Episode> GetAll()
{
List<Episode> listOfEpisodesDeserialized = new List<Episode>();
try
{
listOfEpisodesDeserialized = dataManager.DeserializeEpisode());
}
catch (Exception)
{
throw new SerializerException("Episode.xml", "Error when deserialize");
}
return listOfEpisodesDeserialized;
}
}
public interface IEpisodeRepository<T> : IRepository<T> where T : class
{
List<T> GetAllFeed(string url);
}
public interface IRepository<T> where T : class
{
void Create(T entity);
void Delete(int index);
void Update(int index, T entity);
void SaveChanges();
List<T> GetAll();
int GetIndex(string name);
}
My attempt to solve it with async and await:
I changed the interface method in IRepository to Task<List<T>> GetAll(); and then I changed the method to:
public async Task<List<Episode>> GetAll()
{
List<Episode> listOfEpisodesDeserialized = new List<Episode>();
try
{
listOfEpisodesDeserialized = await Task.Run(() => dataManager.DeserializeEpisode());
}
catch (Exception)
{
throw new SerializerException("Episode.xml", "Error when deserialize");
}
return listOfEpisodesDeserialized;
}
This code won't compile because the method returns
"System.Threading.Tasks.Task<System.Collections.Generic.List<Models.Episode>>" when the field is of type "System.Collections.Generic.List<Models.Episode>".
This code also causes some errors to other methods using GetAll().FirstOrDefault(..).
from Recent Questions - Stack Overflow https://ift.tt/3meu9Nz
https://ift.tt/eA8V8J
Comments
Post a Comment