Specifying a timer object for asynchronously invoking the Expired event

There are times in my application when I need to manually call my timer.

I tried the following:

int originalInterval = t.Interval;
t.Interval = 0;
t.Interval = originalInterval;

but it was consistent.

I created a new timer that inherits from System.Timers.Timer and exposed the "Tick" method, but the problem was that the "Expired" event was then fired synchronously.

When I applied "Tick" with the new Thread, the results were, again, consistent.

Is there a better way to implement it?

+3
source share
3 answers

I had the same problem, so I used AutoResetEvent to find out if Elapsed was successfully launched:

/// <summary>
/// Tickable timer, allows you to manually raise a 'Tick' (asynchronously, of course)
/// </summary>
public class TickableTimer : System.Timers.Timer
{
    public new event ElapsedEventHandler Elapsed;

    private System.Threading.AutoResetEvent m_autoResetEvent = new System.Threading.AutoResetEvent(true);

    public TickableTimer()
        : this(100)
    {
    }

    public TickableTimer(double interval)
        : base(interval)
    {
        base.Elapsed += new ElapsedEventHandler(TickableTimer_Elapsed);
    }

    public void Tick()
    {
        new System.Threading.Thread(delegate(object sender)
        {
            Dictionary<string, object> args = new Dictionary<string, object>
            {
                {"signalTime", DateTime.Now},
            };
            TickableTimer_Elapsed(this, Mock.Create<ElapsedEventArgs>(args));
        }).Start();
        this.m_autoResetEvent.WaitOne();
    }

    void TickableTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        m_autoResetEvent.Set();
        if (this.Elapsed != null)
            this.Elapsed(sender, e);
    }
}
+4

, . , , , , . :

private void Timer_Tick(object sender, EventArgs e)
{
    new Thread(MethodThatDoesTheWork).Start();
}

private void MethodThatDoesTheWork()
{
    // actual work goes here
}

MethodThatDoesTheWork ( , ).

, MethodThatDoesTheWork , :

private void MethodThatDoesTheWork()
{
    new Thread(() =>
    {
         // work code goes here
    }).Start();
}

. , ThreadPool, Task , , .

+3

- . , , , , ( ).

- , "". :

Thread thread = new Thread(myDelegate);
thread.Start();

, myDelegate , :

Thread thread = new Thread(() => myMethod(param1, param2));
thread.Start();
0

Source: https://habr.com/ru/post/1762238/


All Articles