Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been working on a timer in c# just to mess around since I've never done it before. I wanted to have the OnTimedEvents method I was declaring in a separate class as I will be calling it in various other classes for various other tests, but I cannot invoke it properly without getting errors. Specifically, I am getting No Overload Method for Method '' Takes 0 Arguments. I cannot work around this as I have with other methods. This is the code:
class MSOfficeApps {
public static Timer aTimer;
public void appWord() {
var programCS = new Program();
Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
for(int i = 0; i < WordObj.Windows.Count; i++) {
object idx = i + 1;
Microsoft.Office.Interop.Word.Window WinObj = WordObj.Windows.get_Item(ref idx);
Console.WriteLine(WinObj.Document.FullName);
aTimer = new System.Timers.Timer(600000); //Sets timer to 6 minute increments
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent()); //Throwing an error at programCS.OnTimedEvent()
}
}
And this is what I'm trying to call
class Program {
private static void Main(string[] args) {
SearchProcesses sP = new SearchProcesses();
sP.BuildProcessLists();
Console.WriteLine("Press Enter to exit the program...");
Console.ReadLine();
}
public static void OnTimedEvent(Object source, ElapsedEventArgs e) {
Console.WriteLine("Event was raised at {0}", e.SignalTime);
}
}
Please advise :)
Change
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent());
to
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent);
You are invoking programCS.OnTimedEvent, rather than passing it as a reference (and invoking it without arguments), thus the error.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Full instructions: https://pasteboard.co/J2OX03H.png
Running Thread.Sleep on each thread seems to be preventing the Timer's ElapsedEventHandler from recalling Timer_Elapsed (FixedThreads) every x time causing it to print the threads way too fast. My goal is to have ScheduleThreads launch FixedThreads (prints threads info) every 15 seconds even if some of the threads don't finish executing/sleeping on time.
using FT = FixedThreads.FixedThreads;
using Timer = System.Timers.Timer;
namespace ScheduledThreads
{
class ScheduledThreads
{
static void Main(string[] args)
{
var timer = new Timer(15000);
timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
timer.Enabled = true;
while (timer.Enabled)
{
var info = Console.ReadKey(true);
if (info.KeyChar == 'e')
{
timer.Enabled = false;
}
}
}
static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
FT.Main(null);
}
}
}
I call FixedThreads in ScheduledThreads
public class FixedThreads
{
public static void Main(string[] args)
{
Random random = new Random();
ThreadPool.SetMinThreads(100, 100);
for (int task = 0; task < 1000; task++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Execute), task);
Thread.Sleep(random.Next(5, 801)); //this prevents schedule to work if there's more than 10-15 threads/tasks
}
}
static void Execute(object callback)
{
Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId}");
Thread.CurrentThread.Name = callback.ToString();
Console.WriteLine($"Thread Name: {Thread.CurrentThread.Name}");
Console.WriteLine($"Daemon/Background Thread: {Thread.CurrentThread.IsBackground}");
}
}
Are you seeing any output at all from the console? If not you might be deadlocked waiting for the Console.ReadKey to finish before the threads can write to the console output stream. This is because Console.WriteLine and Console.ReadKey both obtain a lock to the same object.
The Console.WriteLine only obtains the lock the first time it outputs to the stream, so an easy way to test that is to add a Console.WriteLine before you do a ReadKey.
You're probably running into the maximum thread count of the default thread pool. It's the default thread pool that handles the Timer.
https://learn.microsoft.com/en-us/dotnet/standard/threading/the-managed-thread-pool
Thread.Sleep will block the thread and is usually a lazy way to get what you're really after. There are better scheduling methods that won't block or be as heavy-weight as a Thread.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am making a food ordering desktop application , so i want to calculate time between ordering food and delivering food so i added timers to the app and made a start and end buttons , on starting i start a time and put it interval value ,make a variable counter, count and save its value on end button to database , what i want to made is to start a new timer dynamically on new orders and when ending an order stop its timer
i tried inserting 3 timers and made variables c1,c2,c3 and made a loop to start timers on every order if interval!=null , but i didn't know how to stop a specific timer on ending the order
code :
int c1=0;
int c2=0;
int c3=0;
private void button_start_Click(object sender, EventArgs e)
{
if (timer1.Interval == null)
{
timer1.Start();
timer1.Interval = 1000;
}
else if (timer2.Interval == null)
{
timer2.Start();
timer2.Interval = 1000;
}
else if (timer3.Interval == null)
{
timer3.Start();
timer3.Interval = 1000;
}
}
Well as you have not shown us any code, let me assume that you at least have a class to encapsulate order.
public class Order
{
public int OrderNumber{get;set;}
///other properties
}
Now if you add following two properties and a method, your problem is resolved.
public class Order
{
public int OrderNumber{get;set;}
//other properties
public DateTime OrderPlacedOn{get;set;}
public DateTime OrderCompletedOn{get;set;}
public TimeSpan TimeToComplete()
{
if(OrderCompletedOn==DateTime.MinValue)//order not completed yet
return TimeSpan.FromSeconds(0);
return OrderCompletedOn - OrderPlacedOn;
}
}
This saves you from keeping countless timers. You can set values of start and complete on clicking of your buttons.
This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 6 years ago.
Fire and forget method in C#
I refered different issues for 'Fire and Forget in C#'
i.e.
Simplest way to do a fire and forget method in C#?
.
.
and few several,
but i have an another issue with the same.i wrote following code
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
//fireAway(i);
Task.Factory.StartNew(() => fireAway(i));
}
Console.WriteLine("Main Finished");
Console.Read();
}
public static void fireAway(int i)
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("FireAway" + i);
}
where i am expecting output like
Main Finished
FireAway0
FireAway1
FireAway2
FireAway3
FireAway4
but output is
Main Finished
FireAway5
FireAway5
FireAway5
FireAway5
FireAway5
very honestly i am new to threading concept, i need help. How can i meet with expected output..?
The threads are started after the loop is finished. When the loop is finished the value of i is 5. You have to capture the value of i before you send it to StartNew(..)
for (int i = 0; i < 5; i++)
{
int tmp = i;
Task.Factory.StartNew(() => fireAway(tmp));
}
You should pass parameter to your method, not use i, because the method will start to execute only after you finish to iterate, see here
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to learn programming and I am starting with a book called Software Development Fundamentals. However I am having loads of difficulty understanding certain subjects. Especially because my native language is not English. I am stuck at the subject (events) and (delegates). I feel like this is to difficult for me, I can not even get this code to work!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lesson02
{
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Changed += new EventHandler(r_Changed);
r.Length = 10;
}
static void r_changed(object sender, EventArgs e)
{
Rectangle r = (Rectangle)sender;
Console.WriteLine(
"Value Changed: Length = {0}",
r.Length);
}
}
class Rectangle
{
public EventHandler Changed;
private double length;
public double Length
{
get
{
return length;
}
set
{
length = value;
Changed(this, EventArgs.Empty);
}
}
}
}
I get this error:
Error 1 The name 'r_Changed' does not exist in the current context 14 59 Lesson02
C# is case-sensitive language. You have defined function as r_changed and using it as r_Changed
Use
r.Changed += new EventHandler(r_changed);
instead of
r.Changed += new EventHandler(r_Changed);
I'm pretty sure you'd know by now that C# is a case sensitive programming language.
This should work
static void r_Changed(object sender, EventArgs e)
{
Rectangle r = (Rectangle)sender;
Console.WriteLine("Value Changed: Length = {0}", r.Length);
}
Notice how r_Changed is capitals (r_changed is what you originally defined)
I would suggest using this because it is easier to read.
There is a little typo mistake in your code. It should be r_Changed instead of r_changed in the your Event Handler.
i.e write
static void r_Changed(object sender, EventArgs e)
in place of
static void r_changed(object sender, EventArgs e)
(Remember C# is Case-sensitive)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
To put it simply,
I start running my C# program in the morning, and the program should show the user a message at 5:45 PM. How can I do this in C#?
Edit: I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task):
private void timerDoWork_Tick(object sender, EventArgs e)
{
if (DateTime.Now >= _timeToDoWork)
{
MessageBox.Show("Time to go home!");
timerDoWork.Enabled = false;
}
}
I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task)
Why? why not timer a best solution? IMO timer is the best solution. but not the way you have implemented. Try the following.
private System.Threading.Timer timer;
private void SetUpTimer(TimeSpan alertTime)
{
DateTime current = DateTime.Now;
TimeSpan timeToGo = alertTime - current.TimeOfDay;
if (timeToGo < TimeSpan.Zero)
{
return;//time already passed
}
this.timer = new System.Threading.Timer(x =>
{
this.ShowMessageToUser();
}, null, timeToGo, Timeout.InfiniteTimeSpan);
}
private void ShowMessageToUser()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.ShowMessageToUser));
}
else
{
MessageBox.Show("Your message");
}
}
Use it like this
SetUpTimer(new TimeSpan(17, 45, 00));
You can use Task Scheduler too.
Also there is a Timer class which can help you
You may easily implement your own alarm class. To start with, you may want to check the Alarm class at the end of the MS article.
You can use a Timer to check each minute if DateTime.Now == (the specific time you want)
This is an example of a code with windows forms
public MainWindow()
{
InitializeComponent();
System.Windows.Threading.DispatcherTimer timer_1 = new System.Windows.Threading.DispatcherTimer();
timer_1.Interval = new TimeSpan(0, 1, 0);
timer_1.Tick += new EventHandler(timer_1_Tick);
Form1 alert = new Form1();
}
List<Alarm> alarms = new List<Alarm>();
public struct Alarm
{
public DateTime alarm_time;
public string message;
}
public void timer_1_Tick(object sender, EventArgs e)
{
foreach (Alarm i in alarms) if (DateTime.Now > i.alarm_time) { Form1.Show(); Form1.label1.Text = i.message; }
}