Reputation: 1777
I'm developing a game. In this game player can click on a button and attack a boss, and he has to wait 5 minutes for the results of the attack.The attack will be executed only after 5 minutes.
So here is my try:
here is my function which is called when the button is clicked:
public static void InsertNewWaitingAttack(string attacker_id, string boss_id, DateTime start, DateTime done)
{
string sql = "INSERT INTO WaitingAttacks (AttackerID,BossID,AttackTime,DoneTime) VALUES (@A_ID,@B_ID,@Start,@Done); ";
sql += "WAITFOR DELAY '000:05:00'; ";
sql += "INSERT INTO BossAttacks (AttackerID,BossID,AttackTime,Damage) VALUES (@A_ID,@B_ID,@Start,@Damage); ";
sql += "DELETE FROM WaitingAttacks WHERE AttackerID=@A_ID AND AttackTime=@Start;";
SqlConnection sc = new SqlConnection(conString);
using (SqlCommand cmd = new SqlCommand(sql, sc))
{
cmd.Parameters.AddWithValue("A_ID", attacker_id);
cmd.Parameters.AddWithValue("B_ID", boss_id);
cmd.Parameters.AddWithValue("Start", start);
cmd.Parameters.AddWithValue("Done", done);
cmd.Parameters.AddWithValue("Damage", 500);
sc.Open();
cmd.ExecuteNonQuery();
sc.Close();
}
}
But when I'm calling this function I'm getting the following error:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
EDIT: To clarify my question, this is an asp.net application. The solution should consider that the server should serve multiple clients.
if the user enters the "Result page" before the execution of the attack, he will see countdown to the execution of the attack.(Which means that the start time of the attack should always be accessible.)
EDIT #2:
The question is still relevant. I didn't find any solution yet.
Upvotes: 0
Views: 2308
Reputation: 56747
How about setting a timer in your code that fires after 5 minutes and performs the INSERT
without WAITFOR
? That way, the program remains responsive and you still get a delay.
I suggest you use System.Timers.Timer
as it runs in a separate thread and can also more easily be configured to be a "one shot" timer.
Another possible way that would make handling multiple boss attach easier would be to create a list of pending "boss attacks" and have a threaded timer work on that list like this:
private class BossAttack
{
public DateTime AttackTime;
//... Other properties
}
List<BossAttack> pendingAttacks = new List<BossAttack>();
// Adding a boss attack
lock (pendingAttacks)
{
pendingAttacks.Add(new BossAttack()
{
AttackTime = DateTime.Now;
...
}
}
The timer could run every second, get all boss attacks older than 5 minutes and process them:
var currentAttacks = (from a in pendingAttacks where (DateTime.Now - a.AttackTime).TotalMinutes() >= 5 select a);
foreach (var currentAttack in currentAttacks)
//...
Upvotes: 4
Reputation: 334
You can try System.Threading.Sleep in an async why see the answer in here:
Upvotes: -2