How come I get no output from this piece of code? - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Timer time = new Timer();
time.Elapsed += new ElapsedEventHandler(action);
time.Interval = 5000;
time.Enabled = true;
time.Start();
}
static void action(Object sender, ElapsedEventArgs args)
{
Console.WriteLine("haha\n");
}
}
}
This piece of code doesnt have any output. Could anyone tell me what the problem is? Thank you very much. I followed exact code on MSDN.. http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.71).aspx

Timer goes out of scope immediately and thus is never called. The program exits before it has a chance to fire the action.
You can make your main method sleep by adding this after time.start():
TimeSpan interval = new TimeSpan(0, 0, 2);
Thread.Sleep(interval);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
class Program
{
static void Main(string[] args)
{
while(true)
{
Timer time = new Timer();
time.Elapsed += new ElapsedEventHandler(action);
time.Interval = 100;
time.Enabled = true;
time.Start();
string line = Console.ReadLine(); // Get string from user
if (line == "exit") // Check for exit condition
{
break;
}
}
Console.WriteLine("End of Program\n");
}
static void action(Object sender, ElapsedEventArgs args)
{
Console.WriteLine("haha\n");
}
}

Related

OpenCvSharp VideoWriter writes an empty video

I am trying to read a vide file, resize the frames and write them to an output file:
using System;
using System.Drawing;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace VideoProcessing
{
public class Player
{
private VideoCapture capture;
private VideoWriter writer;
private Mat matInternal;
public Bitmap bmInternal;
private bool bIsPlaying = false;
public Timer MyTimer = new Timer();
const string outname = "output.avi";
OpenCvSharp.Size dsize = new OpenCvSharp.Size(640, 480);
public void InitPlayer(string videoName)
{
capture = new VideoCapture(videoName);
writer = new VideoWriter(outname, FourCC.MJPG, capture.Fps, dsize);
matInternal = Mat.Zeros(dsize, MatType.CV_8UC3);
bmInternal = matInternal.ToBitmap();
var delay = 1000 / (int)capture.Fps;
MyTimer.Interval = delay;
MyTimer.Tick += new EventHandler(mk_onTick());
MyTimer.Start();
}
private Action<object, EventArgs>
mk_onTick()
{
return (object sender, EventArgs e) =>
{
capture.Read(matInternal);
if (matInternal.Empty())
{
Console.WriteLine("Empty frame!");
}
else
{
matInternal.Resize(dsize);
bmInternal = matInternal.ToBitmap();
writer.Write(matInternal);
}
};
}
public void Dispose()
{
capture.Dispose();
writer.Dispose();
}
}
}
This is executed in my main function as follows:
using System;
using System.Drawing;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace VideoProcessing
{
internal class Program
{
private static void Main(string[] args)
{
var videoName = "input.mp4";
var pl = new Player();
pl.InitPlayer(videoName);
// Some other code that executes in the meantime
pl.Dispose();
}
}
}
The writer can get disposed before the video finishes, which is fine because this will later be adapted for live camera video streams. However, the VideoWriter here produces an apparently empty, 0 second long video file. The codec setting does not produce any errors, and the video is only at 24 FPS so it should not be running into any speed issues. What could be causing this?
I think you have to delay your main thread.
By adding Thread.Sleep(2000) for instance.
I try your code with camera and it works well.

How can i run Class Code in extra Thread? [duplicate]

This question already has answers here:
WebBrowser Control in a new thread
(4 answers)
Closed 2 years ago.
i wanna get the content of 100 links as fast as possible. My first thought was to create one thread, that creates 100 Webbrowser objects, let them navigate and collect all html strings in a list. But when i try to run my code i get the error "actual thread is no singlethread-apartment".
I have the following Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
class ClassDriver
{
[STAThread]
public void StartDriver()
{
ClassTest t = new ClassTest();
Thread thread = new Thread(new ThreadStart(t.Collect));
thread.Start();
}
}
class ClassTest
{
private static List<WebBrowser> browsers;
private static List<string> htmls;
private static Stopwatch sw = new Stopwatch();
public void Collect()
{
string[] link = { "", "" };
sw.Start();
htmls = new List<string>();
browsers = new List<WebBrowser>();
for (int a = 0; a < 100; a++)
{
browsers.Add(new WebBrowser());
browsers.Last().DocumentCompleted += ClassGetRanking_DocumentCompleted;
browsers.Last().Navigate(link[0] + (a + 1) + link[1]);
}
}
private void ClassGetRanking_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (sender as WebBrowser);
htmls.Add(b.DocumentText);
if (htmls.Count == browsers.Count)
{
sw.Stop();
}
}
}
}
The STAThread attribute you applied on StartDriver() method has no effect on the threads created by your own application.
You need to make them STA yourself by calling SetApartmentState() before calling Start()
Thread thread = new Thread(new ThreadStart(t.Collect));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Ref:
https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.setapartmentstate

Continuous Async Ping inside a Windows Service

I need to monitor a list of hosts continuously. After N seconds, i need to check the list again. So, I tried to use the async ping inside a Windows Service.
I tried to follow tips from other posts related to the topic, but always my service stops shortly after starting it.
There are a problem with await in "OnElapsedTime" function.
Any one have an idea what is wrong? Bellow my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net.NetworkInformation;
namespace PingAsyncService
{
public partial class HyBrazil_Ping : ServiceBase
{
Timer timer = new Timer();
List<string> IPList = new List<string>(); //List of IPs
public HyBrazil_Ping()
{
IPList.Add("192.168.0.1");
IPList.Add("192.168.0.254");
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000; //number in miliseconds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private async void OnElapsedTime(object source, ElapsedEventArgs e)
{
//WriteToFile("Service is recall at " + DateTime.Now);
var ResultList = await PingAsync();
foreach(PingReply reply in ResultList)
{
WriteToFile(reply.Address.ToString() + ";" + reply.Status.ToString());
}
}
private async Task<PingReply> PingAndProcessAsync(Ping pingSender, string ip)
{
var result = await pingSender.SendPingAsync(ip, 2000);
return result;
}
private async Task<List<PingReply>> PingAsync()
{
Ping pingSender = new Ping();
var tasks = IPList.Select(ip => PingAndProcessAsync(pingSender, ip));
var results = await Task.WhenAll(tasks);
return results.ToList();
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
Thanks a lot!
In one of the comments you mentioned the error message as
"An asynchronous call is already in progress. It must be completed or canceled before you can call this method."
Chances are, the Ping object does not let simultaneous asynchronous calls.
Using a new Ping object everytime, on each call, might help as below.
private async Task<List<PingReply>> PingAsync()
{
// Ping pingSender = new Ping();
var tasks = IPList.Select(ip =>
{
using (var p= new Ping())
{
return PingAndProcessAsync(p, ip);
}
});
var results = await Task.WhenAll(tasks);
return results.ToList();
}

Running programs on a daily task / cron job?

What exactly is involved when you schedule a task or chron job? I have an application that my manager wants to run daily at a certain time, the application relies on user input but its designed to save user preferences and load those in as well, as soon as the user clicks a button it will perform the task. How do I go about forcing this to happen daily, assuming all data entered is valid. This is in MVC / ASP.NET so it would be on windows. But if someone can explain how it works with cron jobs in linux I can figure it out from there as well. Do i need to write a script that calls my mvc code? or any suggestions?
This is a sample windows service that run every day on given set of time, i think this will help you.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace DemoWinService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
System.Timers.Timer _timer;
List<TimeSpan> timeToRun = new List<TimeSpan>();
public void OnStart(string[] args)
{
string timeToRunStr = "19:01;19:02;19:00"; //Time interval on which task will run
var timeStrArray = timeToRunStr.Split(';');
CultureInfo provider = CultureInfo.InvariantCulture;
foreach (var strTime in timeStrArray)
{
timeToRun.Add(TimeSpan.ParseExact(strTime, "g", provider));
}
_timer = new System.Timers.Timer(60 * 100 * 1000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
ResetTimer();
}
void ResetTimer()
{
TimeSpan currentTime = DateTime.Now.TimeOfDay;
TimeSpan? nextRunTime = null;
foreach (TimeSpan runTime in timeToRun)
{
if (currentTime < runTime)
{
nextRunTime = runTime;
break;
}
}
if (!nextRunTime.HasValue)
{
nextRunTime = timeToRun[0].Add(new TimeSpan(24, 0, 0));
}
_timer.Interval = (nextRunTime.Value - currentTime).TotalMilliseconds;
_timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Enabled = false;
Console.WriteLine("Hello at " + DateTime.Now.ToString()); //You can perform your task here
ResetTimer();
}
}
}

Background Agent Not Performing.: Windows Phone 8

NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.

Categories