|
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!
|
|
|
|
|
Hello!
I'm a beginner and I follow a tutorial for creating the splash screen. Event if I call the APplication.Run myself, it work's and the abord only exit the splash screen.
How can I move the long running task to a background thread ? I'm a bit lost
Thanks!
|
|
|
|
|
That's fairly easy:
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!
|
|
|
|
|
DoWork runs for a million seconds.
for (int i = 0; i < 1000000; i++) {
Thread.Sleep(1000);
work.ReportProgress(i / 10000, $"An object of any type ...: {i}");
}
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
|
|
|
|
|
It's a long running job!
"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!
|
|
|
|
|
Trying to extend tutorial code without first studying the basic aspects of the topics it covers is, usually, going to result in problems. In this case, we can't "see" the tutorial, and be more specific.
There are lots of good resources for understanding threading in C#; for specific issues, like thread-thread interaction, and UI thread interaction with created threads, start here: [^], and, [^]
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
Hi.
I have created an app that modifies the config file of another app and modifies some data in SQL Server. I'm using Visual Studio 2019 with forms in C# . When I run it in my computer it works fine, but when I run it on another computer (without Visual Studio) it gives the message: "To run this application you must install .NET. Would you like to download it now?"
Does anyone know what I must include in my app to resolve this issue?
Thanks.
|
|
|
|
|
It's telling you to install the .NET Framework version you wrote the app against.
|
|
|
|
|
|
The obvious requirement is to install the framework and other essentials the development machine uses on the 'other' machine. Strategies;
1) synchronize windows updates: as of the May 2019 update Win 10 includes FrameWork 4.8
2) get the 'other' machine user to install the missing whatevers, which may require power-user skills and access permissions: [^]
3) use an installer that will ensure the missing whateve4s are installed, like ClickOnce [^] , or, dotNetInstaller [^], or a commercial installer like InstallShield.
3a) compare ClickOnce with the Win installer: [^]
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
If you are using .NET Core or .NET 5 or 6 you can create a self-contained exe which includes all of the .NET Core/5/6 framework required.
"Time flies like an arrow. Fruit flies like a banana."
|
|
|
|