I am wondering if this scenario will be thread safe and if there are problems that I don’t see right now:
From an ASP.net controller, I call a non-static method from a non-static class (this class is in another project, and the class is being injected into the controller).
This method (which is non-static) does some work and calls some other static method passing it userId
Finally, the static method does some work (which requires userId)
I believe this approach is thread safe, and everything will be done correctly if two users call this method at the same time (say, in the same nanosecond). Am I right or wrong? If I am mistaken, what would be the correct way to use static methods in an ASP.net project?
EDIT
Here is the code :)
This is the controller call:
await _workoutService.DeleteWorkoutByIdAsync(AzureRedisFeedsConnectionMultiplexer.GetRedisDatabase(),AzureRedisLeaderBoardConnectionMultiplexer.GetRedisDatabase(), workout.Id, userId);
Here is what DeleteWorkoutByIdAsync looks like:
public async Task<bool> DeleteWorkoutByIdAsync(IDatabase redisDb,IDatabase redisLeaderBoardDb, Guid id, string userId) { using (var databaseContext = new DatabaseContext()) { var workout = await databaseContext.Trenings.FindAsync(id); if (workout == null) { return false; } databaseContext.Trenings.Remove(workout); await databaseContext.SaveChangesAsync(); await RedisFeedService.StaticDeleteFeedItemFromFeedsAsync(redisDb,redisLeaderBoardDb, userId, workout.TreningId.ToString()); } return true; }
As you can see, DeleteWorkoutByIdAsync calls the static method StaticDeleteFeedItemFromFeedsAsync, which looks like this:
public static async Task StaticDeleteFeedItemFromFeedsAsync(IDatabase redisDb,IDatabase redisLeaderBoardDd, string userId, string workoutId) { var deleteTasks = new List<Task>(); var feedAllRedisVals = await redisDb.ListRangeAsync("FeedAllWorkouts:" + userId); DeleteItemFromRedisAsync(redisDb, feedAllRedisVals, "FeedAllWorkouts:" + userId, workoutId, ref deleteTasks); await Task.WhenAll(deleteTasks); }
And here is the static method DeleteItemFromRedisAsync, which is called in StaticDeleteFeedItemFromFeedsAsync:
private static void DeleteItemFromRedisAsync(IDatabase redisDb, RedisValue [] feed, string redisKey, string workoutId, ref List<Task> deleteTasks) { var itemToRemove = ""; foreach (var f in feed) { if (f.ToString().Contains(workoutId)) { itemToRemove = f; break; } } if (!string.IsNullOrEmpty(itemToRemove)) { deleteTasks.Add(redisDb.ListRemoveAsync(redisKey, itemToRemove)); } }