473,396 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Console app async control

Hi all.
A win gui has to run a console (cmd) app, desirably the cmd window is
hidden, which I will do by placing outside the view area.
The GUI must be able to parse the output from cmd and do various things
like show a progress meter etc. It should also be able to gracefully
close the cmd window if it hangs or user needs the thread to abort.
Would I be correct in assuming the cmd should be started in a thread
with async coms?
MethodInvoker with BeginInvoke?
Appreciate any pointers to articles on this subject (google search
reveals few).
Thank you.
Sep 9 '07 #1
7 2349
If you look at ProcessStartInfo, you can suppress the visual console
(IIRC) with CreateNoWindow = true, and capture the output by setting
RedirectStandardOutput = false, UseShellExecute = false, and reading
from Process.StandardOutput once you have started the command.

When running a win-ui, the easiest option is to do the reading (from
StandardOutput) on a workder thread (not the UI thread), and then
(when you read something interesting) use yourForm.BeginInvoke() to
notify the UI. There is also an event-driven mechanism
(Process.OutputDataReceived), but this is trickier.

I'll put an example together if you like...

Marc

Sep 9 '07 #2
(exe)

using System;
using System.IO;

class Program {
static int Main(string[] args) {
try {
string root = args.Length == 1 ? args[0] :
Environment.CurrentDirectory;
string[] dirs = Directory.GetDirectories(args[0], "*.*",
SearchOption.AllDirectories);
int count = dirs.Length, lastPercent = -1;
for (int i = 0; i < count; i++) {
int percent = (i * 100) / count;
if (percent != lastPercent) {
Console.WriteLine(percent.ToString() + "%");
}
foreach (string file in Directory.GetFiles(dirs[i])) {
Console.WriteLine(file);
}
}
return 0;
} catch (Exception ex) {
Console.Error.WriteLine(ex.Message);
return -1;
}
}
}

(winform)

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

class SomeForm : Form {
static void Main() {
Application.EnableVisualStyles();
using (Form f = new SomeForm()) {
Application.Run(f);
}
}

Button goStop;
BackgroundWorker worker;
const string BUTTON_TEXT = "Go";
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
goStop = new Button();
goStop.Text = BUTTON_TEXT;
goStop.Click += new EventHandler(goStop_Click);
Controls.Add(goStop);
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
worker.DoWork+=new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new
ProgressChangedEventHandler(worker_ProgressChanged );
worker.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(worker_RunWorkerCom pleted);
}

void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e) {
goStop.Text = BUTTON_TEXT;
if (e.Cancelled) {
this.Text = "cancelled";
} else if ((int) e.Result == 0) {
this.Text = "complete";
} else {
this.Text = "error " + e.Result.ToString();
}
}

void worker_ProgressChanged(object sender,
ProgressChangedEventArgs e) {
goStop.Text = e.ProgressPercentage.ToString() + "%";
}

void goStop_Click(object sender, EventArgs e) {
if (worker.IsBusy) {
worker.CancelAsync();
} else {
worker.RunWorkerAsync();
}
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
string exe = @"c:\walker.exe", root = @"c:\develop\t";
ProcessStartInfo psi = new ProcessStartInfo(exe, root);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
using(Process proc = Process.Start(psi))
using(StreamReader reader = proc.StandardOutput) {
worker.ReportProgress(0);
Regex re = new Regex(@"\d{1,3}%");
int index = 0;
while (!reader.EndOfStream) {
if (worker.CancellationPending) {
proc.Kill();
e.Cancel = true;
break;
}
string line = reader.ReadLine();
if (re.IsMatch(line)) {

worker.ReportProgress(int.Parse(line.TrimEnd('%')) );
} else {
if (index++ % 20 == 0) {
this.Invoke((MethodInvoker)delegate {
this.Text = line;
});
}
}
}
if (!e.Cancel) {
e.Result = proc.ExitCode;
}

}
}
}

Sep 9 '07 #3
Marc Gravell wrote:
>
I'll put an example together if you like...

Marc
Thank you so much Marc. You have made the task very easy for me to
implement. On the few google results that I have read on the subject, it
is indicated that getting the output from the CMD window is unreliable
to say the least. This is a problem that the previous implimentation
had. So it will be interesting to see how well it works if you like I
will stay in touch.

Am trying to improve a situation whereby the previous method used to
occasionally hang when they used the cmd output. I am not sure whether
they used sync or async comms in that case.
Thanks again, Al.
Sep 9 '07 #4
I did some more playing with this, and it looks like (irritatingly) in
the event of a hang, the Begin... approach is more stable... sorry to
confuse things! I'll see if I can get that working...

Marc

Sep 10 '07 #5
Marc Gravell wrote:
I did some more playing with this, and it looks like (irritatingly) in
the event of a hang, the Begin... approach is more stable... sorry to
confuse things! I'll see if I can get that working...

Marc
OK, but are you saying that the method can hang due to comms problems?
Sep 10 '07 #6
On Sep 10, 2:25 pm, Alistair George <non...@xtra.co.nzwrote:
Marc Gravell wrote:
I did some more playing with this, and it looks like (irritatingly) in
the event of a hang, the Begin... approach is more stable... sorry to
confuse things! I'll see if I can get that working...
Marc

OK, but are you saying that the method can hang due to comms problems?
Be careful when redirecting both standard output and standard error as
there can be a deadlock issue. Check the docs which give some more
details about this issue.

Chris

Sep 11 '07 #7
Chris Dunaway wrote:
On Sep 10, 2:25 pm, Alistair George <non...@xtra.co.nzwrote:
>Marc Gravell wrote:
>>I did some more playing with this, and it looks like (irritatingly) in
the event of a hang, the Begin... approach is more stable... sorry to
confuse things! I'll see if I can get that working...
Marc
OK, but are you saying that the method can hang due to comms problems?

Be careful when redirecting both standard output and standard error as
there can be a deadlock issue. Check the docs which give some more
details about this issue.

Chris
Thanks Chris.
Mark did you want to go any further or shall I proceed with caution
using the code that you promulgated?
Cheers,
Alistair.
Sep 11 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: djw | last post by:
Greetings- I was looking at the ASPN recipe for async I/O and Tkinter: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 I am interested in using the recipe that is provided in...
3
by: mvdevnull | last post by:
static void Main(string args) { DoSomething(); } static void DoSomething() { for (int i=0; i<=10; i++) { CallAsyncMethod(); } } my problem is when i run the app console exists without really...
2
by: Viet | last post by:
I have a couple of questions that hopefully someone could clarify for me. I have an app that uses the threading.timer to constantly poll a scanner to scan in documents. I understand that Async...
6
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to...
0
by: lyl209 | last post by:
Hi - I have 1 console application and 1 web application. Both talk to a web service and I also have some timing code in it. They have the same WSDL and generate the same MyService.cs. *...
1
by: jonathan | last post by:
I need to create a webpage that asynchronously loads a series of user controls onto a page. If the user control take longer than X seconds to load it should display an error message in it place....
12
by: Tomaz Koritnik | last post by:
Is it possible to asynchronously call a method from worker thread so that this method would execute in main-thread? I'm doing some work in worker thread and would like to report progress to main...
13
by: Dog Ears | last post by:
I've got a windows form that monitors the status of employees it polls a database every 2 seconds to fetch updates then update a underlying dataset bound to a grid using Invoke to marshal to the...
4
by: prit | last post by:
As we know ajax resides between server and client and helps the page's partial rendering...so no need to render all the page controls from scratch....so when we know that some controls requires post...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.