Click here to Skip to main content
15,867,453 members
Articles / General Programming / Threads

Multi threading with Windows Forms

Rate me:
Please Sign up or sign in to vote.
4.77/5 (22 votes)
20 Aug 2013CPOL7 min read 69.7K   3.5K   52   11
A Windows threaded client and MVC server demonstrating interaction via XML exchange

Introduction

I've come across a requirement on a number of occasions to produce a Windows application that interacts with a remote web server. The Windows application may be dealing with a web-service, or simply automating form input or screen scraping - what is common is that there is one side of the equation that is web based and therefore can potentially handle multiple requests, thus allowing us to complete the process faster. This article is a project that consists of two parts: a threaded Windows client, and a simple MVC application that it interacts with. As not all remote services allow multiple connections, the project gives the option for running the process in sequential or parallel (threaded) mode. The source code of both projects is attached.

Background

The main concept being introduced in this article is Windows multi-threading. The approach I have taken is one of many open to developers.

The technologies being demonstrated here are:

  • using an HTTPClient in async mode in a thread
  • XML messages
  • interacting with a Windows application main operating thread to update objects on the user interface in a thread safe manner

The threading concept is as follows:

  • create a thread and set its various attributes
  • when the thread completes its work, have it call back into a work-completed method in the main form thread and update the user as required.

Setting things up

The simple server - An MVC app

In order to test our work, and not trigger a denial of service warning (large numbers of multiple threads can do that!), we will create a test harness. In this case, a simple MVC application will suffice. We will create a controller method GetXML that takes in an ID sent by the Windows application, and returns an XML response.

The GetXML method is called like this: http://localhost:4174/home/GetXML?ItemID=23.

And returns output XML like this:

XML
<response type="response-out" timestamp="20130804132059"> 
    <itemid>23</itemid>
    <result>0</result>
</response>

NB: for the purposes of this test, a "result" of 0 = failure, 1 = success.

(1) Create a new MVC app, and add a new controller GetXML. We are also going to put in a small "sleep" command to slow things down a bit and emulate delay over the very busy Interwebs.

C#
public ContentResult GetXML()
{
    // assign post parameters to variables
    string ReceivedID = Request.Params["ItemID"];
    // generate a random sleep time in milli-seconds
    Random rnd = new Random();
    // multiplier ensures we have good breaks between sleeps
    // note that with Random, the upper bound is exclusive so this really means 1..5
    int SleepTime = rnd.Next(1, 2) * 1000;
    // generate XML string to send back
    System.Threading.Thread.Sleep(SleepTime);
    return Content(TestModel.GetXMLResponse(ReceivedID), "text/xml");
} 

(2) Create a model method that takes care of the logic of constructing the XML response to send back. This will take as parameter an ID (int) that represents the identifier of a list of objects/queries that the user is working with. These could be credit cards, websites to scrape, account numbers, etc. In reality you can send in any data you need to work with, and return then to the main calling application.

C#
public static string GetXMLResponse(string ItemID)
{
    // generate a random result code, 0= fail, 1 = success
    // note that with Random, the upper bound is exclusive so this really means 1..2
    Random rnd = new Random();
    string ResultCode = rnd.Next(0, 2).ToString();
    string TimeStamp = GetTimeStamp();

    // create an XML document to send as response
    XmlDocument doc = new XmlDocument();

    // add root node and some attributes
    XmlNode rootNode = doc.CreateElement("response");
    XmlAttribute attr = doc.CreateAttribute("type");
    attr.Value = "response-out";
    rootNode.Attributes.Append(attr);
    attr = doc.CreateAttribute("timestamp");
    attr.Value = TimeStamp;
    rootNode.Attributes.Append(attr);
    doc.AppendChild(rootNode);

    // add child to root node sending back the item ID
    XmlNode dataNode = doc.CreateElement("itemid");
    dataNode.InnerText = ItemID;
    rootNode.AppendChild(dataNode);

    // add our random result
    dataNode = doc.CreateElement("result");
    dataNode.InnerText = ResultCode;
    rootNode.AppendChild(dataNode);
 
    // send back xml
    return doc.OuterXml;
}

The threaded client - A Windows form app

The client is visually quite simple. It contains two edit boxes for input variables, a listview to show the user what is happening, and a checkbox to tell the program if it should run in sequential or threaded mode.

Image 1

We will go through the overall logic first by examining the sequential process, and then look at the threading part.

At the top of the form class we keep track of some variables:

C#
private int RunningThreadCount;
private int RunTimes;
private int TimeStart;

Everything is kicked off by the RunProcess button click event:

C#
TimeStart = System.Environment.TickCount;
InitProcess();
if (chkRunThreaded.Checked)
    RunProcessThreaded(); 
else RunProcess();

We keep track of the start time, and update this when all processes are complete to test how long the process took. We also at this stage call an Init method that sets things up for us, assigning some variables and filling the ListView with values.

C#
// set up some default values
public void InitProcess()
{
    btnExit.Enabled = false;
    btnRunProcess.Enabled = false;
    chkRunThreaded.Enabled = false;
    RunTimes = int.Parse(edtTimesToRun.Text);
    FillListView();

    RunningThreadCount = 0;
}

// fill the ListView with the count items
public void FillListView()
{
    lvMain.Items.Clear();
    for (int i = 0; i < RunTimes; i++)
    {
        ListViewItem itm = new ListViewItem();
        itm.Text = (i+1).ToString();
        itm.SubItems.Add("Pending");
        itm.SubItems.Add("-");
        itm.SubItems.Add("-");
        lvMain.Items.Add(itm);
    } 
}

Let's now look at the sequential RunProcess method. This controls the main body of work for each web request. The number of times to run the process is set by the value of edtTimesToRun.Text which is assigned to the variable RunTimes.

The RunProcess method has a keyword of async - this is important as we are using the await keyword within the RunProcess method. The important part of this code is SendWebRequest - this takes the input, queries the web server, and returns a value that we use to update the UI for the user.

C#
public async void RunProcess()
{
    for (int i = 0; i < RunTimes; i++)  {
        updateStatusLabel("Processing: " + (i + 1).ToString() + 
                 "/" + RunTimes.ToString());
        lvMain.Items[i].Selected = true;
        lvMain.Items[i].EnsureVisible();
        lvMain.Items[i].SubItems[1].Text = "Processing...";
        SimpleObj result = await Shared.SendWebRequest(
                                 new SimpleObj() 
                                     { ItemID = i.ToString(), 
                                       WebURL = edtTestServer.Text}
                                      );
        lvMain.Items[i].SubItems[1].Text = result.ResultCode;
        if (result.ResultCode == "ERR")
            lvMain.Items[i].SubItems[2].Text = result.Message;
    }
    CleanUp();
}

SendWebRequest is located in a separate shared.cs file as it is used from two different places. The shared.cs file also contains a simple object called SimpleObj. This is used to carry data between methods.

C#
public class SimpleObj
{
    public string WebURL; // web address to send post to
    public string ResultCode; // 0 = failure, 1 = success
    // Used to store the html received back from our HTTPClient request
    public string XMLData;
    public string Message; // What we will show back to the user as response
    public string ItemID;
}
// Used to store the ListView item ID/index so
// we can update it when the thread completes    

The SendWebRequest method is again, flagged as async. This will be explained later.

In the SendWebRequest method, we set up an HTTPClient, calling its PostAsync method. Here we are telling the HTTPClient to perform a "POST" action against the server. If you have done web programming before, you will recall setting up a form:

XML
<form action="somedomain.com/someaction?somevalue=134" method="post"> 
<input type="text" id="ItemID">
<input type="submit" value="send">
</form>

That is in effect we are doing here. We create the client object, send in as parameters the URL of the website we want to send the data to, together with the "content", which is the data packet to send. In this case the content simply consists of the parameter ItemID and its value.

C#
HttpResponseMessage response = await httpClient.PostAsync(rec.WebURL, content);

The await keyword tells the code to sit there until with the HTTPClient comes back with a response, or an exception is raised. We examine the response to ensure it is valid (response.IsSuccessStatusCode), and assuming it is, we proceed to take the response content stream and process its XML result. Note the outer Try/Except wrapper - this will catch any HTTP connection errors and report these separately and allow the application to continue working smoothly.

C#
public static async Task<SimpleObj> SendWebRequest(SimpleObj rec)
{
    SimpleObj rslt = new SimpleObj();
    rslt = rec;
    var httpClient = new HttpClient();

    // we send the server the ItemID
    StringContent content = new StringContent(rec.ItemID); 
    try
    {
        HttpResponseMessage response = 
            await httpClient.PostAsync(rec.WebURL, content);
        if (response.IsSuccessStatusCode)
        {
            HttpContent stream = response.Content;
            Task<string> data = stream.ReadAsStringAsync();
            rslt.XMLData = data.Result.ToString();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(rslt.XMLData);
            XmlNode resultNode = doc.SelectSingleNode("response");
            string resultStatus = resultNode.InnerText;
            if (resultStatus == "1")
                rslt.ResultCode = "OK";
            else if (resultStatus == "0")
                rslt.ResultCode = "ERR";
            rslt.Message = doc.InnerXml;
        }
    }
    catch (Exception ex)
    { 
        rslt.ResultCode = "ERR";
        rslt.Message = "Connection error: " + ex.Message;
    } 
    return rslt;
}

So, that is the basic sequential work-flow. Take a list of work items, iterate through them in sequence, call the web server, and parse back the xml response.

As the processes are run sequentially, the overall time taken to complete can be high.

Image 2

Image 3

Now let's run through the RunProcessThread code and see the difference.

Here is our outer wrapper method in the main form:

C#
public void RunProcessThreaded()
{
    updateStatusLabel("Status: threaded mode - watch thread count and list status");
    lblThreadCount.Visible = true;

    for (int i = 0; i < RunTimes; i++)
    {
        updateStatusLabel("Processing: " + (i + 1).ToString() + "/" + RunTimes.ToString());
        lvMain.Items[i].Selected = true;
        lvMain.Items[i].SubItems[1].Text = "Processing...";
        SimpleObj rec = new SimpleObj() { ItemID = i.ToString(), WebURL = edtTestServer.Text };
        CreateWorkThread(rec);
        RunningThreadCount++;
        UpdateThreadCount();
    } 
}   

The critical change is that instead of carrying out the WebRequest task on each loop sequentially, we are passing that task off to the method CreateWorkThread, passing in the required parameters.

C#
public void CreateWorkThread(SimpleObj rec){
    ThreadWorker item = new ThreadWorker(rec);
    //subscribe to be notified when result is ready
    item.Completed += WorkThread_Completed;
    item.DoWork();
} 

This small method creates a new object ThreadWorker, and tells it to call WorkThread_Completed when it is finished. The WorkThread_Completed method in the form simply updates the form UI *in the context of the form thread* and performs some cleanup.

C#
//handler method to run when work has completed
private void WorkThread_Completed(object sender, WorkItemCompletedEventArgs e)
{
    lvMain.Items[int.Parse(e.Result.ItemID)].SubItems[1].Text = e.Result.ResultCode;
    if (e.Result.ResultCode == "ERR")
        lvMain.Items[int.Parse(e.Result.ItemID)].SubItems[2].Text = e.Result.Message;

    RunningThreadCount--;
    UpdateThreadCount();

    if (RunningThreadCount == 0)
    {
        CleanUp();
    }
}

I have created a separate class/file ThreadWorker to manage the thread work - this keeps things separate and clean.

The class has some private members and a public event:

C#
class ThreadWorker
{
    private AsyncOperation op; // async operation representing the work item
    private SimpleObj ARec; // variable to store the request and response details
    public event EventHandler<WorkItemCompletedEventArgs> Completed;
    //event handler to be run when work has completed with a result


    // constructor for the thread. Takes param ID index of the Listview to keep track of.
    public ThreadWorker(SimpleObj Rec)
    {
        ARec = Rec;                 
    } 
}

You will recall that in our main form, when we are creating each thread worker, we set up the thread object, then tell it to DoWork so this is the main kick-off method for the thread object.

C#
public void DoWork()
{
    //get new async op object calling forms sync context
    this.op = AsyncOperationManager.CreateOperation(null);
    //queue work so a thread from the thread pool can pick it up and execute it
    ThreadPool.QueueUserWorkItem((o) => this.PerformWork(ARec)); 
} 

The reason I am using a ThreadPool object is that creating threads is a very expensive operation therefore using the pool means that on completion, threads can be put into a pool to be reused. After being added to the pool, we tell the thread to kick off the method PreformWork. This method calls our shared method SendWebRequest, and when that is finished, calls PostCompleted which gets picked up by the WorkThread_Completed method in the main form class.

C#
private void PostCompleted() //SimpleObj result
{
    // call OnCompleted, passing in the SimpleObj result to it,
    // the lambda passed into this method is invoked in the context of the form UI
    op.PostOperationCompleted((o) => 
      this.OnCompleted(new WorkItemCompletedEventArgs(ARec)), ARec);
}

protected virtual void OnCompleted(WorkItemCompletedEventArgs Args)
{
    //raise the Completed event in the context of the form 
    EventHandler<WorkItemCompletedEventArgs> temp = Completed;
    if (temp != null)
    {
        temp.Invoke(this, Args);
    }
}

Our main form "WorkThread_Completed" method watches each incoming terminated thread, and when they have all completed, runs some cleanup code.

C#
//handler method to run when work has completed
private void WorkThread_Completed(object sender, WorkItemCompletedEventArgs e)
{
    lvMain.Items[int.Parse(e.Result.ItemID)].SubItems[1].Text = e.Result.ResultCode;
    if (e.Result.ResultCode == "ERR")
        lvMain.Items[int.Parse(e.Result.ItemID)].SubItems[2].Text = e.Result.Message;
    RunningThreadCount--;
    UpdateThreadCount();
    if (RunningThreadCount == 0)
    {
        CleanUp();
    }
}  

And that is it, as you can see running threaded adds a bit more code, but dramatically improves performance.

Image 4

Image 5

As I stated at the start of this article, this is but one way of handling a threaded application. Thread pools have their advantages and disadvantages, you need to weigh up your goals and granular needs against the ease of use. If you are interested in this area you should also look at Background worker and if you want to harness the power that is in multi-core CPUs while threading the Task Parallel Library is a great way to go.

(PS: If you found this article useful or downloaded the code please let me know by giving a rating below!) 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer SocialVoice.AI
Ireland Ireland
Allen is CTO of SocialVoice (https://www.socialvoice.ai), where his company analyses video data at scale and gives Global Brands Knowledge, Insights and Actions never seen before! Allen is a chartered engineer, a Fellow of the British Computing Society, a Microsoft mvp and Regional Director, and C-Sharp Corner Community Adviser and MVP. His core technology interests are BigData, IoT and Machine Learning.

When not chained to his desk he can be found fixing broken things, playing music very badly or trying to shape things out of wood. He currently completing a PhD in AI and is also a ball throwing slave for his dogs.

Comments and Discussions

 
Praiseexcellent! Pin
Southmountain19-Mar-22 11:11
Southmountain19-Mar-22 11:11 
GeneralMy vote of 5 Pin
D V L19-Aug-15 20:02
professionalD V L19-Aug-15 20:02 
QuestionExit button Pin
Tomas283-Jun-15 3:26
Tomas283-Jun-15 3:26 
AnswerRe: Exit button Pin
DataBytzAI3-Jun-15 10:35
professionalDataBytzAI3-Jun-15 10:35 
GeneralRe: Exit button Pin
Tomas284-Jun-15 5:26
Tomas284-Jun-15 5:26 
QuestionThis example I liked (HTTP client) Pin
NikolaB1-Dec-14 9:19
NikolaB1-Dec-14 9:19 
QuestionGood intro to threading Pin
Andy Neillans30-Dec-13 20:43
professionalAndy Neillans30-Dec-13 20:43 
AnswerRe: Good intro to threading Pin
DataBytzAI30-Dec-13 21:38
professionalDataBytzAI30-Dec-13 21:38 
QuestionWhy do you do this line? Pin
Sacha Barber20-Aug-13 3:20
Sacha Barber20-Aug-13 3:20 
this.op = AsyncOperationManager.CreateOperation(null);


Could you not just create a new SynchronizationContext() if the current one is null? I don't see why you need that. Could you explain

Other than that nice article
Sacha Barber
  • Microsoft Visual C# MVP 2008-2012
  • Codeproject MVP 2008-2012
Open Source Projects
Cinch SL/WPF MVVM

Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue

My Blog : sachabarber.net

AnswerRe: Why do you do this line? Pin
DataBytzAI20-Aug-13 4:09
professionalDataBytzAI20-Aug-13 4:09 
GeneralMy vote of 4 Pin
fredatcodeproject20-Aug-13 2:01
professionalfredatcodeproject20-Aug-13 2:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.