|
Hi,
I need to do a "cron mechanism" that does not block the entire program. It has to be performed at the time set by the user
int time_stop;
Task.Delay(time_stop).Wait(); .
time_stop is provided by the user. But this approach is not entirely consistent with my assumptions. Can someone guide me.
Sorry, but I'm just learning to code
|
|
|
|
|
You either need to set up a Timer Class (System.Timers) | Microsoft Docs[^] or a BackgroundWorker Class (System.ComponentModel) | Microsoft Docs[^]
Either will do, but without one or the other, you will block the UI thread waiting for the timeout to elapse - which will make it look like the whole application is locked up!
Me? I'd use a background worker and use the Progress reporting mechanism to update the UI thread when necessary:
private void FrmMain_Shown(object sender, EventArgs epp)
{
BackgroundWorker work = new BackgroundWorker();
work.DoWork += Work_DoWork;
work.ProgressChanged += Work_ProgressChanged;
work.RunWorkerCompleted += Work_RunWorkerCompleted;
work.WorkerReportsProgress = true;
work.RunWorkerAsync("A parameter of any type you want to pass it");
}
private void Work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MyTextBox.Text = "Done.";
}
private void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MyTextBox.Text = ($"Progress: {e.ProgressPercentage} - {e.UserState as string}");
}
private void Work_DoWork(object sender, DoWorkEventArgs e)
{
if (sender is BackgroundWorker work)
{
for (int i = 0; i < 1000000; i++)
{
Thread.Sleep(1000);
work.ReportProgress(i / 10000, $"An object of any type you want to pass back to the main thread: {i}");
}
}
}
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
If I use a loop
while (1)
{
Thread.Sleep (1000);
work.ReportProgress (i / 10000, $ "An object of any type you want to pass back to the main thread: {i}");
}
will I suspend the program?
The program is to be executed e.g. every day at 7:00 am
|
|
|
|
|
Not if it's running on a different thread, that's the whole idea.
You app starts with a single thread - the UI thread - which is responsible for updating the display and handling all user inputs: keyboard, mouse, touch screen - all of it.
The whole idea of a BackgroundWorker class is that it starts a new thread on which the long running task executes, leaving the UI thread free to handle user interactions in a timely manner. The Progress reporting mechanism moves the "update" data back to the UI thread so it can be displayed.
Try it: you'll start to see how it works!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
|
To be honest, if you want to execute a program at the same time every day, I wouldn't code for it at all: I'd add it to the Windows task scheduler to be run at that time, or (if it doesn;t need any user interaction) make it a service so the user doesn't have to be logged in.
What are you trying to automate?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Adding posts to wordpress is to be a desktop program not from the page dashboard
|
|
|
|
|
Then why run it at a time when it's likely to be unattended?
I'd break it in two parts: a UI app which "collates" the data, and a service which updates at a specific time.
That way, your users don't have to remember not to close the app, or to open it before they knock off for the day and the service just sits in the background sleeping most of the time.
Use a DB for communication between them for simplicity and it's a relatively painless task?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Sorry but i don't know what is DB
EDIT
database, yeah?
modified 4-Nov-21 7:15am.
|
|
|
|
|
Yep!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I will have to use the Windows service. This will be the best solution.
|
|
|
|
|
For how to enable .NET 5 in VS 2019: [^]. Also, see the weird hack at the end of this post.
Note: the two 'records defined here use positional arguments rather than Property get/set for parameters. that is supposed to confer immutability, and non-destructive mutation (whatever that is). The code below runs without errors.
public record Cat(string Name, int HowHungry);
public record AlleyCat(string Name, int HowHungry, string Color) : Cat(Name, HowHungry);
public void TaleOfTwoCats()
{
Cat cat1 = new Cat("Bonita gatita", 2);
AlleyCat alleycat1 = new AlleyCat("Anhela cabezas de pescado", 99, "stale orangina");
bool iscat1 = cat1 is Cat;
bool isalleycat1 = cat1 is AlleyCat;
bool iscat2 = alleycat1 is AlleyCat;
bool iscat3 = alleycat1 is Cat;
bool issamecat1 = cat1 == alleycat1;
bool issamecat2 = cat1.Equals(alleycat1);
cat1 = alleycat1;
bool iscat4 = cat1 is Cat;
bool isalleycat2 = cat1 is AlleyCat;
bool iscat5 = alleycat1 is AlleyCat;
bool iscat6 = alleycat1 is Cat;
bool issamecat3 = cat1 == alleycat1;
bool issamecat4 = cat1.Equals(alleycat1);
} Note: to make this work in a WinForm 4.8 program, i had to include this:
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit { }
} Weird: there is no reference in the Project to CompilerServices, or top=level using statement invoking it.
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
State1 & state2 will run parallel or State1 will run first and later State2 will run ?
please guide me. thanks
var stage1 = Task.Run(() =>
{
});
var stage2 = Task.Run(() =>
{
});
Task.WaitAll(stage1, stage2);
|
|
|
|
|
Mou_kol wrote: State1 & state2 will run parallel or State1 will run first and later State2 will run ?
Yes.
Or perhaps 2 will run first and 1 later.
There is no way to control what happens with tasks of equal priority: they exist on separate threads, and will be executed when the OS decides it is appropriate , and as a core becomes available. That means that the execution order of the tasks is indeterminate: it cannot be predicted or relied upon.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Task.Run will execute the contained code on the ThreadPool. The TreadPool will allow a number of tasks to run in parallel. So as long as you have not reached this limit and there is a CPU core available, they will execute in parallel.
If you have reached the limit, they might run one by one - and they might delay execution until a thread becomes available. This is typically not something you need to think about, but worth knowing if you have long running operations or if you are queueing a lot of operations on the thread pool - for example looping over a collection and running something for each item. If you need to do the latter, look into "Task Parallel Library"[^]
|
|
|
|
|
Ask yourself: Why am I doing this?
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Here is two approaches to read multiple files by a multiple threads but getting problem.
please tell me what is the problem in the below code
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}
please see the full code and tell me what is wrong there.
class Program
{
static string folderPath;
static readonly string fileContent = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
static void Main(string[] args)
{
folderPath = "F:\VirusScan";
int counter = 1000;
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}
Console.ReadKey();
}
static void GenerateVirusFile(int i)
{
string filePath = $@"{folderPath}\TestForVirusScan_{i}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
var timer = Stopwatch.StartNew();
while (true)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms");
break;
}
else
{
Thread.Sleep(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}");
}
}
}
doing same job Using task
class Program
{
static string folderPath;
static readonly string fileContent = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
static void Main(string[] args)
{
folderPath = "F:\VirusScan";
int counter = 1000;
List<Task> tasks = new List<Task>();
for (int i = 1; i <= counter; i++)
{
Task newTask = new Task((x) => GenerateVirusFile(x), i);
tasks.Add(newTask);
}
foreach (var task in tasks)
{
task.Start();
}
Task.WaitAll(tasks.ToArray());
Console.ReadKey();
}
public static void GenerateVirusFile(object i)
{
string filePath = $@"{folderPath}\TestForVirusScan_{i}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
var timer = Stopwatch.StartNew();
while (true)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms");
break;
}
else
{
Thread.Sleep(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}");
}
}
}
Thanks
|
|
|
|
|
|
|
Reading multiple files at the same time is slower than reading them one after another. Limited channels. Context / thread switching. HDD head contention.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
If I were you and for some reason I needed to read/write multiple files in parallel (though Gerry is right when it comes to writing files to traditional hard disk drives), instead of the methods you use, I would simplify things by using the Parallel.For or the Parallel.Foreach method.
|
|
|
|
|
Hi,
On my Win Form App, I'm starting a new thread for my Splash Screen (and when loading some component on my main form).
I wanna be able to update a label on the new thread. I try with invoke, delegate and similar thing but i'm not able to do it.
I'm now out of ressource. Can anyone help me with this ? May be my code is not the best to do this ?
The frmSplashScreen form containt a label name metroLabel4 and this is the one I want to update from the other form (when I load the component, where the "// Code for loading component go here" is.
Thanks in advance
public frmMain()
{
Thread t = new Thread(new ThreadStart(Loading));
t.Start();
InitializeComponent();
t.Abort();
}
void Loading()
{
frmSplashScreen frm = new frmSplashScreen();
Application.Run(frm);
}
|
|
|
|
|
How many times do you want to "update" the label? If it's only once, pass the text for the label in the splash form's constructor. And why you just don't "show" the splash screen escapes me; A splash screen usually doesn't "do" anything except keep the user from thinking the app is hung. Add a timer to the flash form if you want it to animate something. Use a concurrent collection (queue) or an observable collection if you want to share information.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Hello!
Update should be like 4 or 5 times. As a beginner, that's the tutorial I find that make it run insted of showing it.
I try to add a timer but don't know why, the splash screen don't show when I have it.
Thanks!
|
|
|
|
|
Firstly, you shouldn't be calling Application.Run yourself - you should only have the one message loop. I'm not sure what effect that would have, since there can only be one MainWindow object, and that's already in use ... if that worked (which it doesn't) then your thread Abort would either kill the main form and app, or possibly make it impossible to exit the main process properly at all.
Secondly, you can't update a control except from the thread on which it was created - normally the one and only UI thread - so accessing the label on the splash form is going to be problematic - if you could find it, which you can't since the only reference you have is local to the loading method.
The normal way to do this is to Show the Splash screen, and move the long running task to a background thread, which updates the splash screen via progress reports to the UI thread - and I'd move the "loading" code into the Form.Load or Form.Shown event handlers instead of in the main form constructor and use a BackgroundWorker class instance to offload the long job to a second thread, using the Progress reporting of that class to get information back to the UI thread.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|