Use a other Method in a static method - c#

How can I use the method ChangeText in my static method timer_Elapsed?
public Load()
{
InitializeComponent();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
// I can't transfer parameters here
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Its underlined in red. I need a object reference?
ChangeText();
}
public void ChangeText()
{
label1.Text = label1.Text + ".";
}

I don't see any reason why timer_Elapsed should be static. So simply remove it.
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
ChangeText(); //Its not underlined anymore, you have an object reference
}
Another way would be to make ChangeText static. But that won't work since you want to set a Label's Text, so you need an instance of the Form anyway.

As first, your method (timer_Elapsed) could not me static, in order to use an instance property (label1)
There is an other problem in your code: Timer create an other thread, an most of windows control properties can be modified only by UI thread. Your code will throw a CrossThreadException.
In order to resolve your problem , you should modify your code with this:
if(this.InvokeRequired) {
BeginInvoke(
new MethodInvoker(delegate { label.Text+="."; }));
} else {
label.Text+=".";
}
Regards

Make ChangeText a static method.
public static void ChangeText()

Only static methods are called from a static method,
Either make your ChangeText() method to static or make your time_Elapsed method to non-static

You cannot call instance methods in static ones without creating an instance first. You have to create an instance of the class this method belongs to. like below:
var instance = new Load();
instance.ChangeText();
Update:
As other answers suggested, you should reconsider defining timer_Elapsed as static.

Hi Can you try like below:
public Load()
{
InitializeComponent();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
// I can't transfer parameters here
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
private delegate void ChangeLabel();
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
var ChangeLabel = new ChangeLabel(ChangeText);
this.BeginInvoke(ChangeLabel);
}
private void ChangeText()
{
label1.Text = label1.Text + ".";
}

Related

Timer variable is null which is declared for countdown timer?

I have this code which is used for countdown in C#. I can't seem to find why my variable t is null. I tried this code on a separate project and it works well. I tried to incorporate it into another project and it says that variable t is null.
public partial class tracker : Form
{
System.Timers.Timer t;
int h1, m1, s1;
public tracker()
{
InitializeComponent();
}
private void tracker_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
btnLogin.Enabled = false;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectedText = DateTime.Now.ToString("MM/dd/yyyy\n");
richTextBox2.SelectedText = "Time In\n";
richTextBox3.SelectedText = DateTime.Now.ToString("HH:mm:ss\n");
richTextBox4.SelectedText = "\n";
richTextBox5.SelectedText = "\n";
}
}
You are getting error t as null, because t.Start() is calling before instantiation of Timer object t.
To solve this issue, either instantiate before t.start() or create an object inside the constructor.
Like
public tracker()
{
InitializeComponent();
//Here you can instantiate Timer class
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void tracker_Load(object sender, EventArgs e)
{
//Do NOT create object of Timer class here
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
...
}

Call a method from another method

I have this code:
public void StartTimer()
{
var timer = new DispatcherTimer();
timer.Tick += Something;
timer.Interval = new TimeSpan(0, 0, 0, 3);
timer.Start();
}
private async void Something()
{
//code goes here....
}
The problem is that I get this error:
No overload for 'Something' matches delegate
'System.EventHandler'
My question is probably basic: why I get this error and how can I fix it...
The property Tick is of type EventHandler.
The signature of EventHandler is:
public delegate void EventHandler(
Object sender,
EventArgs e
)
Which means your Something method must match this signature. Change it to:
public void Something(Object sender, EventArgs e) { ... }
Alternatively, if you can't change the signature of that method, you can create a new delegate that calls your method.
timer.Tick += (s, e) => Something();
The DispatcherTimer.Tick event expects a handler that takes an object and an EventArgs argument:
private void Something(object o, EventArgs e)
{
// implementation
}
The signature of Something does not match that specific event. Look into the documentation for that event to see how it's done.
Try This
public void StartTimer()
{
var timer = new DispatcherTimer();
timer.Tick += Something;
timer.Interval = new TimeSpan(0, 0, 0, 3);
timer.Start();
}
private async void Something(Object sender, EventArgs e)
{
//code goes here....
}

Should I put a BackgroundWorker inside a Singleton?

I have an application that takes a Wireshark capture file and feeds it (all the containing packets) into a network adapter.
Currently my application is a big mess - countless global variables & every task opened within a seperate BackgroundWorker instance etc...
To clarify - the purpose of using BackgroundWorkers here (more specifically the DoWork, RunWorkerCompleted events and the WorkerReportsProgress property) is to prevent the packet feeding operations from freezing my UI. To stop an operation, I need access to these workes - for now, global variables are used to achieve this.
So the question is - should I place my BackgroundWorker objects inside a Singleton-type class and then call this object when necessary?
From a technical point of view is possible, after all the singleton pattern is a design pattern that restricts the instantiation of a class to one object
you can try something like this
public class BackWorkerSingleton
{
private BackgroundWorker _backgroundWorker;
private static readonly object myLock = new object();
private static BackWorkerSingleton _backWorkerSingleton = new BackWorkerSingleton();
public delegate void ReportProgressEventHandler(object sender,MyEventsArgs e);
public event ReportProgressEventHandler ReportProgress = delegate{ };
private BackWorkerSingleton()
{
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
}
void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.ReportProgress( this, new MyEventsArgs(){Progress = e.ProgressPercentage});
}
void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// do your work here
}
public void StartTheJob()
{
_backgroundWorker.RunWorkerAsync();
}
public static BackWorkerSingleton Worker
{
get
{
lock (myLock)
{
if (_backWorkerSingleton == null)
{
_backWorkerSingleton = new BackWorkerSingleton();
}
}
return _backWorkerSingleton;
}
}
}
class MyEventsArgs:EventArgs
{
public int Progress { get; set; }
}
and here the report progress
private void Form1_Load(object sender, EventArgs e)
{
BackWorkerSingleton.Worker.ReportProgress += new BackWorkerSingleton.ReportProgressEventHandler(Worker_ReportProgress);
}
void Worker_ReportProgress(object sender, MyEventsArgs e)
{
}
and call it like this
BackWorkerSingleton.Worker.StartJob()

An error No overload for 'timer_Tick' matches delegate 'System.EventHandler<object>'

I am not sure what is wrong with my code can someone help fix the error? The error is in the timer.Tick() line. It's supposed to make a stopwatch.
namespace App3
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private int myCount;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += new EventHandler<object>(timer_Tick);
timer.Interval = TimeSpan.FromSeconds(5);
timer.Start();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
}
private void timer_Tick(object sender, EventArgs e)
{
myCount++;
Label.Text = myCount.ToString();
}
}
DispatcherTimer.Tick is an EventHandler, not an EventHandler<object>.
You need to change your code to specify this correctly:
timer.Tick += new EventHandler(timer_Tick);
Note that this can also be written in short form, which is typically safer:
timer.Tick += timer_Tick;
Delegate types are not required when attaching events, the compiler can figure it out for you. Try this instead:
timer.Tick += timer_Tick;
As for why you get the error currently, the EventHandler delegate is declared like this:
public delegate void EventHandler<TEventArgs>(
Object sender,
TEventArgs e
)
This means the type you put in the brackets represents the second argument in the function.
So when you type EventHandler<object>, the compiler looks for a function like timer_Tick(Object sender, object e) which it does not find, hence the error. To use the full delegate type, it would have to be EventHandler<EventArgs>
Instead of new EventHandler<object>, do new EventHandler. Or alternatively just put += timer_Tick;.
I solved the same issue with two small changes:
1) Change second argument to type object:
INSTEAD OF THIS:
private void timer_Tick(object sender, EventArgs e)
USE THIS:
private void timer_Tick(object sender, **object** e)
2) Simplify the
INSTEAD OF THIS:
timer.Tick += new EventHandler<object>(timer_Tick);
USE THIS:
timer.Tick += timer_Tick; // as suggested by WildCrustacean above

C# Executing a method with intervals using system.threading.timer

Hello
Lets say I have a console application, that looks like this
class Program
{
static void Main(string[] args)
{
}
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
}
I wan't to execute my DoSomething method every 10'th second by using System.Threading.timer. Can anyone give an example of how that is done?
Thanks in advance :)
Timer timer1 = new Timer(10000);
timer1.Enabled = true;
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Start();
static void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//Do Something
}
The documentation page for the System.Threading.Timer class has a lengthy, good example.

Categories

Resources