本文整理汇总了C#中System.Timers.Timer.Close方法的典型用法代码示例。如果您正苦于以下问题:C# Timer.Close方法的具体用法?C# Timer.Close怎么用?C# Timer.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Timers.Timer
的用法示例。
在下文中一共展示了Timer.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: scheduleEvent
public static int scheduleEvent(Event newEvent, uint intervalMinutes, bool snapToHour=false, ushort minimumPlayers=0, uint durationSeconds=0, uint[] countDownTimes=null)
{
ScheduledEvent scheduledEvent = (durationSeconds == 0 ? new ScheduledEvent(newEvent, intervalMinutes, minimumPlayers, countDownTimes) : new ScheduledEvent(newEvent, intervalMinutes, minimumPlayers, countDownTimes, durationSeconds));
if(snapToHour)
{
int minuteToStart = (int)(intervalMinutes * (DateTime.Now.Minute/intervalMinutes) + intervalMinutes);
int timeToWait = (minuteToStart * 60000) - (DateTime.Now.Minute*60000 + DateTime.Now.Second*1000 + DateTime.Now.Millisecond);
Timer waitTimer = new Timer(timeToWait);
waitTimer.AutoReset = false;
waitTimer.Elapsed += delegate
{
scheduledEvent.beginRecurrence();
waitTimer.Close();
};
waitTimer.Start();
}
else
scheduledEvent.beginRecurrence();
scheduledEvents.Add(scheduledEvent);
return scheduledEvents.IndexOf(scheduledEvent);
}
示例2: DelayedCall
public static Timer DelayedCall(double delay, TimerCallback callback)
{
Timer newTimer = null;
Timer returnTimer = null;
try
{
newTimer = new Timer(Math.Max(delay, 1));
newTimer.AutoReset = false;
newTimer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs args)
{
try
{
callback();
}
catch (Exception ex)
{
Logger.Fatal(Strings.UnhandledExceptionCaught, ex.ToString());
Environment.FailFast(Strings.UnhandledExceptionCaught2 + "\r\n" + ex.ToString());
}
});
newTimer.Enabled = true;
returnTimer = newTimer;
newTimer = null;
}
finally
{
if (newTimer != null)
{
newTimer.Close();
}
}
return returnTimer;
}
示例3: DrawQuery
/// <summary>
/// Creates a new <c>DrawQuery</c> that refers to the specified feature type(s),
/// drawing the results of the spatial query to the specified display.
/// </summary>
/// <param name="index">The index to query</param>
/// <param name="display">The display to draw to</param>
/// <param name="style">The drawing style</param>
/// <param name="types">The type(s) of spatial feature to draw</param>
public DrawQuery(ISpatialIndex index, ISpatialDisplay display, IDrawStyle style, SpatialType types)
{
m_Display = display;
m_Style = style;
m_DoPaint = false;
Timer t = new Timer(500);
t.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
t.Start();
index.QueryWindow(m_Display.Extent, types, OnQueryHit);
t.Close();
display.PaintNow();
}
示例4: CheckUrl
/// <summary>
/// Start the url relocation check
/// </summary>
public void CheckUrl()
{
//check if attempt<max_attempts
//if not add urc to queue
//and start a timer until there are no open urc's left
//
//if attempts slot left just connect
/*
if (QueueTimer != null)
{
QueueTimer.Stop();
QueueTimer.Dispose();
QueueTimer.Close();
}
*/
if (url == "")
{
Console.WriteLine("empty url to check ?");
return;
}
bool attempts_left = false;
lock (AttemptsLock)
{
if (Attempts < MaxAttemptsNum)
attempts_left = true;
}
if (attempts_left)
{
Attempts++;
}
else
{
lock (QueueLock)
{
Queue.Add(this);
}
if (QueueTimer == null)
{
Console.WriteLine("Attempts overflow: starting queue timer");
QueueTimer = new Timer(QueueUpdateInterval);
QueueTimer.AutoReset = true;
QueueTimer.Elapsed += delegate(object sender, ElapsedEventArgs e)
{//an interesting question is if this block is locked ? ;-)
//Console.WriteLine("queue timer interval elapsed\nAttempts running: " + Attempts + "\nItems in Queue: " + Queue.Count);
lock (QueueLock)
{
if (Attempts < MaxAttemptsNum && Queue.Count > 0)
{
//now use up all free slots by activating new checks and increase the attempts num
int end = MaxAttemptsNum - Attempts;
if (end > Queue.Count)
end = Queue.Count;
//Console.WriteLine("checking " + end + " queue items.");
for (int i = 0; i < end; i++)
{
//lock (AttemptsLock)
//{
Attempts++;
//}
Queue[i].Connect();
}
Queue.RemoveRange(0, end);
}
if (Queue.Count == 0)
{
Console.WriteLine("finished all urls in the relocation check queue.\nStopping Timer.");
QueueTimer.Stop();
QueueTimer.Dispose();
QueueTimer.Close();
QueueTimer = null;
//GC.Collect();
}
}
};
QueueTimer.Start();
}
return;
}
Connect();
}
示例5: removeTime
public void removeTime(Timer t)
{
bool fail = false;
//int index = 0;
do
{
try
{
var copy = new List<TimerEvent>();
for(var i=_timers.Count - 1;i>=0;i--)
{
//index = i;
if(i <= _timers.Count)
{
copy.Add(_timers[i]);
}
}
var a = copy.FirstOrDefault(c => c != null && c.Timer == t);
_timers.Remove(a);
fail = false;
}
catch(Exception e)
{
//t.Close();
fail = true;
//Console.WriteLine("[" + DateTime.Now + "] - Error removetime fail : " + t.GetHashCode() + " // Ex : " + e.Message + " // index : " + index + " // " + _timers.Count);
//var a2 = _timers.Find(c => c != null && c.Timer == t);
//_timers.Remove(a2);
}
} while (fail);
t.Close();
}
示例6: SendConnectionRequest
//.........这里部分代码省略.........
byte[] reply_message_byte = new byte[3072];
byte[] bytes = new byte[3072];
stream.Read(reply_message_byte, 0, reply_message_byte.Length);
int i = 0;
int num_bytes_read = 0;
do
{
if (stream.DataAvailable)
{
stream.Read(bytes, 0, bytes.Length);
Array.Copy(bytes, 0, reply_message_byte, num_bytes_read, i);
num_bytes_read += i;
}
else
{
Thread.Sleep(10);
if (!stream.DataAvailable)
{
break;
}
i = 1;
}
} while (i != 0);
timer.Stop();
string reply = ASCIIEncoding.Unicode.GetString(reply_message_byte);
string[] sub_reply = reply.Split('\n');
// if the peer have accepted the connection request
if (sub_reply[0].Substring(0, 4) == "Nova" && sub_reply[1].Substring(0, 10) == "CONNECT_OK")
{
Utilities.Log.Write("Connection established with " + PeerIP, Utilities.Log.LogCategory.ConnectionRequests);
// create a new peer object
Objects.Peer peer = new Objects.Peer(PeerIP, client, stream);
peer.ID = "EMPTY";
// send a EI-message
string eiMessParam1;
string eiMessParam2;
if (Global.MessageEncryptionEnabled == true)
{
eiMessParam1 = "y";
eiMessParam2 = string.Format("{0},{1}",
Utilities.Converterer.ConvertByteToHex(peer.MyAsymmetricEncryptionKey.N),
Utilities.Converterer.ConvertByteToHex(peer.MyAsymmetricEncryptionKey.E));
}
else
{
eiMessParam1 = "n";
eiMessParam2 = string.Empty;
}
// create and send a EI-message
Messages.IMessage eiMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.EI, false, eiMessParam1, eiMessParam2);
peer.Send(eiMess);
// add the peer in the list of the peers
Lists.PeersList.AddPeer(peer);
}
else
{
stream.Close();
client.Close();
}
timer.Close();
}
catch
{
if (client != null)
{
client.Close();
}
if (stream != null)
{
stream.Close();
}
Utilities.Log.Write("The connection request hasn't been sent, probably the peer (" + PeerIP + ") is offline or disconnected", Utilities.Log.LogCategory.Error);
}
}));
t.Name = "MessageSender_Connection_Request_Sending";
t.IsBackground = true;
t.Start();
}
示例7: Main
static void Main(string[] args)
{
try
{
// Add to the console
Console.Title = "Sius";
Console.WriteLine("Sius");
Console.Write("Press any key to exit ..." + Environment.NewLine);
Time = DateTime.Now;
// Check if we are logging
if (!string.IsNullOrEmpty(SiusConf.GetSetting.String("logging")))
SiusLog.Logging = true;
// Check if we want to clear the log before starting
if (SiusConf.GetSetting.Boolean("clearlog"))
SiusLog.ClearLogFile();
// Create the SQLite database and tables
SQLite.Connect();
// Log that Sius has successfully started
SiusLog.Log(SiusLog.INFORMATION, "server","Sius successfully started.");
// Initialize the Transmission Control Protocol (TCP) connection
Listen tcp = new Listen();
tcp.StartListening();
// Start the Ping timer
System.Timers.Timer SendPing = new System.Timers.Timer();
SendPing.Elapsed += new ElapsedEventHandler(Protocol.Ping.OnTimedEvent);
if (SiusConf.GetSetting.Integer("ping") >= 10)
SendPing.Interval = SiusConf.GetSetting.Integer("ping") * 1000;
else
SendPing.Interval = 150000; // 150 seconds
SendPing.Enabled = true;
SendPing.Start();
// Start the Scorereset timer
System.Timers.Timer Scorereset = new System.Timers.Timer();
Scorereset.Elapsed += new ElapsedEventHandler(Protocol.Scorereset.OnTimedEvent);
if (SiusConf.GetSetting.Integer("scorereset") >= 1)
Scorereset.Interval = SiusConf.GetSetting.Integer("scorereset") * 3600000;
else
Scorereset.Interval = 1209600000; // 2 weeks
Scorereset.Enabled = true;
Scorereset.Start();
// Wait until we're told to exit the program
while (Running == true)
{
// press any key to exit
Console.ReadKey(true);
Running = false;
SendPing.Close();
Scorereset.Close();
}
// Cleanup and end all TCP connections
Sius.Connected = false;
SiusLog.Log(SiusLog.INFORMATION, "server","Exiting");
tcp.RequestStop();
// Append a line to the log to mark the end of a run.
SiusLog.DirectLogToFile("-----------------------------------------------------");
}
catch (Exception e)
{
// Log any unexpected errors
SiusLog.Log(SiusLog.ERROR, "server", "Error: " + e.StackTrace);
}
}
示例8: Launch
internal static void Launch()
{
Application.CurrentCulture = CultureInfo.InvariantCulture;
Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
splash = new SplashForm();
splash.Show();
Timer timer = new Timer();
//Configure this timer to restart each second ( 1000 millis)
timer.Interval = 1000;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
//splash.Refresh();
//Application.DoEvents();
Application.DoEvents();
MainModule.Initialize("data");
splash.SetLoadProgress(50);
splash.Refresh();
Application.DoEvents();
UpdaterHelper.UpdateInfo info;
info = UpdaterHelper.CheckFromUpdates();
Application.DoEvents();
if (info.UpdateAvailable)
{
UpdateForm updateForm;
updateForm = new UpdateForm(info);
updateForm.ShowDialog();
Application.DoEvents();
}
splash.SetLoadProgress(60);
splash.Refresh();
Application.DoEvents();
IconsManager.Initialize();
Application.DoEvents();
MainForm main = new MainForm();
//if (runSingleInstance)
//{
// main.HandleCreated += new EventHandler(main_HandleCreated);
//}
GC.Collect();
timer.Stop();
timer.Close();
splash.SetLoadProgress(100);
splash.Refresh();
Application.DoEvents();
splash.Close();
splash = null;
Application.DoEvents();
Application.Run(main);
}
示例9: GetAlbumInfo
public void GetAlbumInfo()
{
try
{
_searchTimer = new Timer { Enabled = false, Interval = TimeLimit };
_searchTimer.Elapsed += TimerElapsed;
_searchTimer.Start();
GetAlbumInfoWithTimer();
}
finally
{
if (_searchTimer != null)
{
_searchTimer.Stop();
_searchTimer.Close();
}
}
}
示例10: DoPublish
private void DoPublish(string subject, Message message, uint delay = 0)
{
if (Message.RECEIVE_ONLY == subject)
{
throw new InvalidOperationException(Resources.NatsMessagingProvider_PublishReceiveOnlyMessage);
}
log.Debug(Resources.NatsMessagingProvider_PublishMessage_Fmt, subject, delay, message);
string formattedMessage = NatsCommand.FormatPublishMessage(subject, message);
log.Trace(Resources.NatsMessagingProvider_LogSent_Fmt, formattedMessage);
if (delay == 0)
{
Write(formattedMessage);
}
else
{
Timer delayTimer = null;
try
{
delayTimer = new Timer(delay) { AutoReset = false };
delayTimer.Elapsed += (object sender, ElapsedEventArgs args) => Write(formattedMessage);
delayTimer.Enabled = true;
delayTimer = null;
}
finally
{
if (delayTimer != null)
{
delayTimer.Close();
}
}
}
}
示例11: submit
public void submit(byte[] bytes, UdpUser socket)
{
SlidingWindow window = new SlidingWindow();
int extraBytes = bytes.Length % 1024;
int loop = bytes.Length / 1024;
//wait for reply messages from server and send them to console
Task.Factory.StartNew(async () =>
{
while (true)
{
var received = await socket.Receive();
//lock (window)
{
if (received.packet.AckNumber == window.Window.Peek().SequenceNumber)
{
window.Forward();
window.LastAck = received.packet.AckNumber;
Console.WriteLine(String.Format((received.packet.AckNumber / (Decimal)(loop + 1)).ToString("P", CultureInfo.InvariantCulture)));
}
}
}
});
for (int i = 0; i <= loop; i++)
{
Packet packet = new Packet();
if (i == loop)
{
packet = new Packet(loop + 1, 0, true, false, extraBytes, Extensions.SubArray(bytes, 1024 * (loop), extraBytes));
}
else
{
packet = new Packet(i + 1, 0, false, false, Convert.ToInt32(1024), Extensions.SubArray(bytes, 1024 * i, 1024));
}
socket.Send(packet.BuildPacket());
Timer timer = new Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.Start();
while (!window.CanForward && timer.Enabled == true)
{
}
if (timer.Enabled == false)
{
i = window.Window.Peek().SequenceNumber - 2;
//i = i - 5;
//if (i < -1) { i = -1; }
}
else
{
lock (window)
{
if ((window.Window.Count == 0) ||
(packet.SequenceNumber > window.Window.Min().SequenceNumber))
{
window.InsertPacket(packet);
}
}
}
timer.Close();
}
}
示例12: EnterGameModus
public void EnterGameModus()
{
// Generate the map.
mapController.GenerateMap();
// Render the map.
view.RenderGameScreen(mapController.map);
// Start the interval timer.
intervalTimer = new Timer(interval);
intervalTimer.Elapsed += OnInterval;
intervalTimer.AutoReset = true;
intervalTimer.Enabled = true;
// Loop through input
bool quit = false;
while (!quit)
{
ConsoleKeyInfo key = Console.ReadKey(false); // Get string from user
switch (key.KeyChar)
{
case '1':
case '2':
case '3':
case '4':
case '5':
break;
case 'q':
quit = true;
break;
default:
view.RenderInvalidInputWarning(key.KeyChar);
break;
}
}
// Loop has been ended so the user has quitted. End the game.
// Kill the timer.
intervalTimer.Enabled = false;
intervalTimer.Close();
intervalTimer = null;
view.RenderEndScreen();
}
示例13: Start
public void Start()
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, PORT);
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
System.Timers.Timer timerAlive = new System.Timers.Timer();
timerAlive.Elapsed += new ElapsedEventHandler(OnTimerAlive);
timerAlive.Interval = 1000;
timerAlive.Enabled = true;
try
{
socket.Bind(localEndPoint);
socket.Listen(100);
while (!_cancel)
{
_signal.Reset();
socket.BeginAccept(new AsyncCallback(ConnectCallback),
socket);
_signal.WaitOne();
}
}
catch (SocketException ex)
{
OnServerError();
if (socket.IsBound)
socket.Shutdown(SocketShutdown.Both);
string msg = "Network Error:\n" + ex.Message;
MessageBox.Show(msg, Info.Title(),
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
timerAlive.Close();
socket.Close();
foreach (var client in clients.ToArray())
ClientRemove(client);
}
}
示例14: WriteToDatabase
//.........这里部分代码省略.........
oracleConnection = this._oracleConnection;
}
else
{
oracleConnection = new OracleConnection(this._connectionString);
}
OracleCommand commandOracle = new OracleCommand(BuildBulkInsertCommandText(), oracleConnection) { BindByName = true };
commandOracle.Parameters.AddRange(BuildCommandParameter());
//需要绑定值的参数
IList<OracleParameter> parameterCollection = new List<OracleParameter>();
foreach (OracleParameter parameter in commandOracle.Parameters)
{
if (!this._dicNoInitValueParameters.ContainsKey(parameter.ParameterName))
{
parameterCollection.Add(parameter);
}
}
int intBatchIndex = 0x0;
int intLineNo = 0x0;
CopiedRowCount = 0x0;
try
{
//开始记时
stopwatch.Start();
oracleConnection.Open();
while (ReadSource())
{
if (timeIsOver)
{
throw new OracleBulkInsertException(BulkInsertCode.ExecuteTimeOut, (this._timeOut / OracleBulkInsert.ONE_SECONDS).ToString());
}
//绑定参数值
SetParameterValue(intBatchIndex, parameterCollection);
//设定行号
if (this._insertRowNumber)
{
((object[])commandOracle.Parameters[_rowNumberColumn].Value)[intBatchIndex] = this._startRow - 1 + ++intLineNo;
}
//批次累加
++intBatchIndex;
//未达到提交批次
if (intBatchIndex % this._batchSize != 0) continue;
commandOracle.ArrayBindCount = intBatchIndex;
commandOracle.ExecuteNonQuery();
//设置提交行数
CopiedRowCount += intBatchIndex;
//恢复批次
intBatchIndex = 0x0;
}
if (intBatchIndex % this._batchSize != 0)
{//提交最后不足一批的剩余记录
commandOracle.ArrayBindCount = intBatchIndex;
commandOracle.ExecuteNonQuery();
//设置提交行数
CopiedRowCount += intBatchIndex;
}
}
catch (OracleBulkInsertException ex)
{
throw new OracleBulkInsertException(ex.Message, CopiedRowCount);
}
catch (Exception ex)
{
throw new OracleBulkInsertException(ex.ToString(), CopiedRowCount);
}
finally
{
//关闭定时器
timer.Enabled = false;
timer.Close();
timer.Dispose();
//释放连接
oracleConnection.Close();
oracleConnection.Dispose();
//关闭数据源
CloseDatasource();
//关闭秒表
stopwatch.Stop();
TakeMilliseconds = stopwatch.ElapsedMilliseconds;
}
}
示例15: Run
//.........这里部分代码省略.........
stopwatch = Stopwatch.StartNew();
while (testRun.IterationsExecutedSuccessfully < this.Iterations &&
testRun.State != TestRunState.RunFailed)
{
// Sleep between iterations but not on first iteration.
if (testRun.IterationsExecutedSuccessfully != 0)
{
Thread.Sleep((int)this.DelayBetweenIterationsInMS);
}
response = null;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(testRun.RestUri);
httpWebRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.UserAgent = Dns.GetHostName();
httpWebRequest.Method = "Get";
//if (runAsUserCredential == null)
//{
// httpWebRequest.UseDefaultCredentials = true;
// testRun.RunAsUserName = WindowsIdentity.GetCurrent().Name.Split('\\').LastOrDefault();
//}
//else
//{
// testRun.RunAsUserName = runAsUserCredential.UserName;
// httpWebRequest.PreAuthenticate = true;
// httpWebRequest.UseDefaultCredentials = false;
// httpWebRequest.Credentials = new NetworkCredential(@"CMPVT02\dciBuild", "CSIBuild!");
//}
testRun.RunAsUserName = userName;
httpWebRequest.PreAuthenticate = true;
httpWebRequest.UseDefaultCredentials = false;
httpWebRequest.Credentials = new NetworkCredential(userName, userPassword);
timeoutTimer = new Timer(this.ApiSla.Value.TotalMilliseconds);
timeoutTimer.Elapsed += delegate(object sender, ElapsedEventArgs args)
{
Console.WriteLine(
"\n!!!Timeout: Request {0} (Iteration:{1}) has not returned in SLA:{2} seconds; Total Lapsed time:{3} seconds\n",
httpWebRequest.RequestUri,
testRun.IterationsExecutedSuccessfully,
this.ApiSla.Value.TotalSeconds,
stopwatch.Elapsed.TotalSeconds);
};
timeoutTimer.Start();
// Default is 100,000 = 100 seconds. changing it to 3,600,000 = 1 Hour.
// TODO: Make this a parameter value instead of hard coded.
httpWebRequest.Timeout = 3600000;
stopwatch.Start();
response = (HttpWebResponse)httpWebRequest.GetResponse();
stopwatch.Stop();
testRun.ProcessResponse(response);
}
}
catch (System.Net.WebException ex)
{
if (stopwatch.IsRunning)
{
stopwatch.Stop();
}
if (ex.Response != null)
{
testRun.ProcessResponse((HttpWebResponse)ex.Response);
}
else
{
testRun.State = TestRunState.RunFailed;
testRun.ErrorMessage = ex.ToString();
}
}
catch (Exception ex)
{
if (stopwatch.IsRunning)
{
stopwatch.Stop();
}
testRun.State = TestRunState.RunFailed;
testRun.ErrorMessage = ex.ToString();
}
finally
{
if (timeoutTimer != null)
{
timeoutTimer.Close();
timeoutTimer.Dispose();
}
testRun.TotalExecutionTime = stopwatch.Elapsed;
testRun.AverageExecutionTime = testRun.IterationsExecutedSuccessfully == 0
? TimeSpan.Zero
: TimeSpan.FromTicks(
testRun.TotalExecutionTime.Ticks /
testRun.IterationsExecutedSuccessfully);
}
return testRun;
}