So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:
namespace PortScannerTool
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
tb_portstatus.Text = "Click the button to query ports";
dns_info.Text = tb_portstatus.Text;
}
private void Btn1_Click(object sender, RoutedEventArgs e)
{
CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
Thread query_status = new Thread(cmdobj.Runcmd);
query_status.Start();
tb_portstatus.Text = "Done!";
}
}
}
namespace PortQueryApp
{
class CmdExec
{
string command;
public string dnsText;
public string querystatusText;
public CmdExec(string ip, string port)
{
this.command = $"-n {ip} -o {port}";
}
public void Runcmd()
{
Process proc = new Process();
proc.StartInfo.FileName = "PortQry.exe";
proc.StartInfo.Arguments = this.command;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string query_output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
string resolve_pass = "Name resolved";
string resolve_fail = "Failed to resolve IP address to name";
if (query_output.Contains(resolve_pass))
{
this.dnsText = "Resolved!";
}
if (query_output.Contains(resolve_fail))
{
this.dnsText = "Resolve Failed!";
}
this.querystatusText = "Done!";
}
}
}
dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.
So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.
Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!
Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:
class CmdExec : MainWindow
{
//Do stuff
}
instead?