Let me know if you have a better approach: I have a small C# bot that check for an…
- User
Let me know if you have a better approach:
I have a small C# bot that check for an available date/time and book it if any, it uses 2 external APIs which many other users use so it is a race, My main goal is to get an available date/time that I didn’t use before if possible.
private static readonly Dictionary<string, List> TestedDateTimes = new();
public async void Main() { // Checking string? date, time; while (true) { (date, time) = await SelectAvailableDateTime().ConfigureAwait(false); if (date != null && time != null) break;
codeawait Task.Delay(3000).ConfigureAwait(false); } //Do something with the date/time...}
public async Task<(string date, string time)> SelectAvailableDateTime() { var date = await GetNonUsedRandomDate().ConfigureAwait(false); if (date == default) return default;
codevar time = await GetNonUsedRandomTimeByDate(date).ConfigureAwait(false); if (time == null) return default; if (!TestedDateTimes.ContainsKey(date)) TestedDateTimes[date] = new List<string>(); if (!TestedDateTimes[date].Contains(time)) TestedDateTimes[date].Add(time); return (date, time);} private async Task<string?> GetNonUsedRandomDate() { var allDates = await GetAllDates().ConfigureAwait(false);
codevar availableDates = allDates ?.Where(d => d.AppointmentDateType == AppointmentDateType.Available && (_applicant.Members.Count < 2 || d.SingleSlotAvailable)) .ToArray(); if (availableDates == null || availableDates.Length == 0) return default; var nonUsedDates = availableDates.Where(d => !TestedDateTimes.ContainsKey(d.DateText)).ToArray(); if (nonUsedDates.Length == 0) nonUsedDates = availableDates; // So if the user uses a custom date selector and there is no date fulfill his needs, search on all return (GetRandomDate(nonUsedDates) ?? GetRandomDate(availableDates))?.DateText; - Assistant
Your current approach seems mostly fine, but can potentially be improved by using some minor changes:
-
I would change
Mainto be asynchronous and useTask.Runrather thanawaitdirectly. This makes it easier to handle any potential issues if you need to callMainfrom another async method. -
From an overall design perspective, it would be cleaner to use a class (e.g.
DateTimeBooking) that encapsulates all the required methods and keeps track of theTestedDateTimes. This would make it easier to unit test the functionality and potentially reuse it in other projects.
Here's the suggested refactored version:
csharp -