user2454137
user2454137

Reputation: 33

Fire and Forget in C#

Is there any event in C# like fire and forget for every min???

fire this method every minute.

    public void Earning()
    {
        var data= new Bussinesslayer().Getdata();
    }

Upvotes: 2

Views: 770

Answers (3)

Dmitry Ledentsov
Dmitry Ledentsov

Reputation: 3660

Use, for example, Rx

Observable.Interval(TimeSpan.FromMinutes(1))
          .Subscribe(x => Earning());

No threading needed

Upvotes: 1

V Maharajh
V Maharajh

Reputation: 9629

public void Earning()
{
    var data= new Bussinesslayer().Getdata();

    // Wait a minute
    Task.Delay(TimeSpan.FromMinutes(1)).Wait();
    // Re-run this method
    Task.Factory.StartNew(() => Earning());
}

You'll need these includes:

using System;
using System.Threading.Tasks;

Upvotes: 0

Avi Turner
Avi Turner

Reputation: 10456

You can use the Timer class:
Declaration:

System.Timers.Timer _tmr;

Initialization:

_tmr = new System.Timers.Timer();

Setting up:

//Assigning the method that will be called
_tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed);
//Setting the interval (in milliseconds):
_tmr.Interval = 1000;

Starting the timer:

_tmr.Start();

The function that will should have the same signature as in the example below:

void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  this.Earning();
  //please note that here you are in another thread.
}

If you want to stop the timer you can use:

_tmr.Stop();

Upvotes: 8

Related Questions