/// <summary> /// Adding\updating user's profile by directory. /// </summary> /// <param name="user">User profile.</param> /// <param name="directory">Users storage.</param> public static async void SetProfileAsync(User user, string directory) { await Task.Run(() => { // Lock thread not saved hashset lock (LoadingLockedDirectories) { // Create file path. string filePath = directory + GetUserFileName(user); // Lock directory. LoadingLockedDirectories.Add(filePath); // Set profile synchronically. bool result = SetProfile(user, directory); // Unlock directory. LoadingLockedDirectories.Remove(filePath); // Inform subscribers about location unlock. DirectoryLoadingFinished?.Invoke(directory, result ? 1 : 0, result ? 0 : 1); } }, Session.Current.TerminationTokenSource.Token); }
/// <summary> /// Loading users data from directory. /// </summary> /// <param name="directory"></param> public static async void LoadProfilesAsync(string directory) { // Validate directory. if (!Directory.Exists(directory)) { Console.WriteLine("ERROR (ACAPI 0): USERS LOADING NOT POSSIBLE. DIRECTORY NOT FOUND."); // Inform subscribers about finish. DirectoryLoadingFinished?.Invoke(directory, 0, 0); return; } // Block if certain directory already in loading process. if (LoadingLockedDirectories.Contains(directory)) { Console.WriteLine("ERROR (ACAPI 10): Directory alredy has active loading process. Wait until finish previous one. ({0})", directory); // Inform subscribers about finish. DirectoryLoadingFinished?.Invoke(directory, 0, 0); return; } // Lock directory. LoadingLockedDirectories.Add(directory); // Detect files in provided directory. string[] xmlFiles = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly); int loadingSucceed = 0; int loadingFailed = 0; // Running async task with loading of every profile. await Task.Run(() => { // Init encoder. XmlSerializer xmlSer = new XmlSerializer(typeof(User)); // Deserialize every file to table if possible. foreach (string fileDir in xmlFiles) { // Open stream to XML file. using (FileStream fs = new FileStream(fileDir, FileMode.Open)) { User loadedUser = null; try { // Try to deserialize routing table from file. loadedUser = xmlSer.Deserialize(fs) as User; // Add user to tables. AddToLoadedData(loadedUser); // Up counter. loadingSucceed++; } catch (Exception ex) { // Up counter. loadingFailed++; // Inform. Console.WriteLine("ERROR(ACAPI 20): Profile damaged. Reason:\n{0}\n", ex.Message); } } // Share quant to other processes. Thread.Yield(); } // Remove directory from blocklist. LoadingLockedDirectories.Remove(directory); // Inform subscribers about location unlock. DirectoryLoadingFinished?.Invoke(directory, loadingSucceed, loadingFailed); }, Session.Current.TerminationTokenSource.Token); }