本文整理汇总了C#中System.Threading.Timer.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Timer.Dispose方法的具体用法?C# Timer.Dispose怎么用?C# Timer.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Timer
的用法示例。
在下文中一共展示了Timer.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Worker
public void Worker()
{
if (Config.CoreTest != 0)
Logger.Log.Warn("Running in CoreTest mode ({0})", Config.CoreTest);
SendCounter.Refresh();
ErrorCounter.Refresh();
LastSendCount = 0;
LastErrorCount = 0;
var timer = new Timer(GetStatus, null, 0, Config.NotifyPeriod * 1000);
do
{
ProcessMassMail();
Thread.Sleep(2000);
//Trigger GC to reduce LOH fragmentation
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
}
while (!_threadStop);
timer.Dispose();
}
示例2: DisposeTimer
public static void DisposeTimer(Timer timer)
{
Check.Require(timer, "timer");
var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
timer.Dispose(waitHandle);
waitHandle.WaitOne(1000);
}
示例3: SocketListenerThreadStart
//Let's talk with the client!
private void SocketListenerThreadStart()
{
int size = 0;
//1KB buffer is enough?
Byte[] byteBuffer = new Byte[1024];
_lastReceiveDateTime = DateTime.Now;
_currentReceiveDateTime = DateTime.Now;
int _timeout = 10 * 60 * 1000; //10min of timeout
Timer t = new Timer(new TimerCallback(CheckClientCommInterval), null, _timeout, _timeout);
while (!_stopClient)
{
try
{
size = _clientSocket.Receive(byteBuffer);
_currentReceiveDateTime = DateTime.Now;
parseClientCMD(byteBuffer, size);
}
catch (SocketException)
{
//there are problems...better delete the connection
_stopClient = true;
_markedForDeletion = true;
}
}
t.Dispose();
t = null;
}
示例4: ShowRace
public void ShowRace(IRace race)
{
int turn = 0;
this.drawTrack(race, turn, "Press any key to start the race...");
Console.ReadKey(true);
using (Timer timer = new System.Threading.Timer(
(o) =>
{
turn++;
this.drawTrack(race, turn, "(Press any key to skip)");
}
))
{
timer.Change(this.speed, this.speed);
while (turn < race.TurnCount - 1 && !Console.KeyAvailable) ; // check if race is finished or if there's anything in the input buffer
while (Console.KeyAvailable)
{
Console.ReadKey(true); // clear the input buffer
}
timer.Dispose();
}
this.drawTrack(race, race.TurnCount - 1, string.Format("The winner is {0}\n\n", race.Winner.Name) + this.leftMargin + "Press any key to continue...");
Console.ReadKey(true);
}
示例5: Main
static void Main(string[] args)
{
// Create an event to signal the timeout count threshold in the timer callback.
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create an inferred delegate that invokes methods for the timer.
TimerCallback tcb = statusChecker.CheckStatus;
// Create a timer that signals the delegate to invoke CheckStatus after one second,
// and every 1/4 second thereafter.
Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);
// When autoEvent signals, change the period to every 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
示例6: Run
public override void Run()
{
Trace.TraceInformation("Worker started processing of messages");
// Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
Client.OnMessage((msg) =>
{
Timer renewTimer = new Timer(UpdateLock, msg, 1000, updateLockLeaseInMilliSec); //every 30 seconds after 1 sec
try
{
// Process the message
Trace.TraceInformation("Processing Service Bus message: " + msg.SequenceNumber.ToString());
string reportReq = (string)msg.Properties["reportReq"];
if (!CreateReport(reportReq))
msg.DeadLetter();
msg.Complete();
}
catch (Exception e)
{
// Handle any message processing specific exceptions here
Trace.TraceError("Message processing exception: " + e.Message);
msg.Abandon();
}
renewTimer.Dispose();
});
CompletedEvent.WaitOne();
}
示例7: Method_2
public static void Method_2()
{
try
{
TimerCallback t = new TimerCallback(Method_1);
Timer tmr = new Timer(t);
ConsoleKeyInfo cki = new ConsoleKeyInfo();
tmr.Change(0, 1);
Console.WriteLine("Press UP Arrow");
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.UpArrow)
{
tmr.Dispose();
if(miliseconds > 300)
{
Console.WriteLine("Looser!!!");
}
}
Console.WriteLine("Result = {0} milisecond", miliseconds);
while (true)
{
if (cki.Key == ConsoleKey.UpArrow)
{
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
示例8: Work
public void Work()
{
_charactersControl.CharacterSelected += character =>
{
_charactersControl.Hide();
if (CharacterSelected != null)
CharacterSelected(character);
};
_charactersControl.DeleteCharacter += character =>
{
DI.Get<IGetStringControl>().Show("Удаление персонажа",
"Введите имя удаляемого персонажа.",
charName => character.Name == charName ? string.Empty : "Неправильное имя персонажа",
charName => { DeleteCharacter(character); });
};
_charactersControl.CancelDeleteCharacter += CancelDeleteCharacter;
_timer = new Timer(state => {
UpdateCharacters();
},
null,
Settings.Default.CharactersRefreshInterval,
Settings.Default.CharactersRefreshInterval);
_charactersControl.ControlClosed += () => {
if (_timer != null)
_timer.Dispose();
};
_charactersControl.Show(UpdateCharacters);
}
示例9: GetRequestTime
/// <summary>
/// Считает время ожидания ответа на запрос к http серверу
/// </summary>
/// <param name="address">Url адрес</param>
/// <param name="maxRequestTime">Максимальное время ожидания ответа. -1 для бесконечного времени ожидания.</param>
/// <returns>Время запроса в мс</returns>
internal static int GetRequestTime(string address, RequestParams requestParams, int maxRequestTime, out Exception outEx)
{
int result = -1;
Exception innerEx = null;
using (var request = new HttpRequest())
{
request.UserAgent = HttpHelper.ChromeUserAgent();
EventWaitHandle wh = new AutoResetEvent(false);
var requestThread = new Thread(() =>
{
var watch = new Stopwatch();
watch.Start();
try
{
string resultPage = request.Get(address, requestParams).ToString();
}
catch (Exception ex) { innerEx = ex; }
result = Convert.ToInt32(watch.ElapsedMilliseconds);
watch.Reset();
wh.Set();
});
requestThread.Start();
var stoptimer = new System.Threading.Timer((Object state) =>
{
requestThread.Abort();
wh.Set();
}, null, maxRequestTime, Timeout.Infinite);
wh.WaitOne();
stoptimer.Dispose();
}
outEx = innerEx;
return result;
}
示例10: ImageLoader
static ImageLoader()
{
_expirationTimer = new Timer(_ => RemoveExpiredCaches(), null,
TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
App.ApplicationFinalize += () => _expirationTimer.Dispose();
StartDecodeThread();
}
示例11: ThreadingTimer
private static void ThreadingTimer()
{
Console.WriteLine("StartTimer {0:T}", DateTime.Now);
Timer t1 = new Timer(TimeAction, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(3));
Thread.Sleep(15000);
t1.Dispose();
}
示例12: Main
static void Main(string[] args)
{
Timer t = new Timer(TimerMethod, null, 0, 1000);
Console.WriteLine("Main thread {0} continue...", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10000);
t.Dispose();
}
示例13: Main
public static void Main(string[] args)
{
var logger = new NoDebugLogger();
var bus = RabbitHutch.CreateBus("host=localhost",
x => x.Register<IEasyNetQLogger>(_ => logger));
int messageCount = 0;
var timer = new Timer(state =>
{
Console.Out.WriteLine("messages per second = {0}", messageCount);
Interlocked.Exchange(ref messageCount, 0);
}, null, 1000, 1000);
bus.Subscribe<TestPerformanceMessage>("consumer", message => Interlocked.Increment(ref messageCount));
Console.CancelKeyPress += (source, cancelKeyPressArgs) =>
{
Console.Out.WriteLine("Shutting down");
bus.Dispose();
timer.Dispose();
Console.WriteLine("Shut down complete");
};
Thread.Sleep(Timeout.Infinite);
}
示例14: AddTask
public void AddTask(
string taskName,
Action task,
TimeSpan dueTime,
TimeSpan period,
TaskConcurrencyOptions taskConcurrencyOptions)
{
var scheduledTask = new ScheduledTask(taskName, task, taskConcurrencyOptions);
var taskTimer =
new Timer(
RunTask,
scheduledTask,
Timeout.Infinite,
Timeout.Infinite);
if (!_tasksTimers.TryAdd(taskName, taskTimer))
{
taskTimer.Dispose();
throw new Exception("Could not add task " + taskName + ".");
}
taskTimer.Change(dueTime, period);
}
示例15: StartNewDelayed
public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) {
// Validate arguments
if (factory == null)
throw new ArgumentNullException(nameof(factory));
if (millisecondsDelay < 0)
throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
// Create the timed task
var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
var ctr = default(CancellationTokenRegistration);
// Create the timer but don't start it yet. If we start it now,
// it might fire before ctr has been set to the right registration.
var timer = new Timer(self => {
// Clean up both the cancellation token and the timer, and try to transition to completed
ctr.Dispose();
(self as Timer)?.Dispose();
tcs.TrySetResult(null);
}, null, -1, -1);
// Register with the cancellation token.
if (cancellationToken.CanBeCanceled) {
// When cancellation occurs, cancel the timer and try to transition to canceled.
// There could be a race, but it's benign.
ctr = cancellationToken.Register(() => {
timer.Dispose();
tcs.TrySetCanceled();
});
}
// Start the timer and hand back the task...
timer.Change(millisecondsDelay, Timeout.Infinite);
return tcs.Task;
}