1

My question is i want to execute some operations like fetching the data ( format is string )from some URL . and i want run this process to be background. i have to call this operations whenever user needs this. like if a user clicks a button specified for this operation, it should execute the function and provide result to that user. Problem is when ever executing this no other program should not get interrupted. I want to run this Asynchronous way . i want to return the result which is downloaded from the URL Here is my solution using thread

namespace xyz
{

    public class newWinForm : Form
    {
        SomeClass someClass = new SomeClass();

        public newWinForm()
        {
          Thread backgroundThread = new Thread(DoWork);
          backgroundThread.IsBackground = true;
          backgroundThread.Start();

         }
         void DoWork()
         {
            try
            {
              Console.WriteLine("Doing some work...");
              using(WebClient cl = new WebClient())
              {
               string result = cl.DownloadString("http://www.......com");
              } 
              Thread.Sleep(1000);
             }
             finally
             {
               Console.WriteLine("This should be always executed");
             }
          }
         private void getDataFrmUrlButton_Click(object sender, EventArgs e)
         {
          Thread backgroundThread = new Thread(DoWork);
          backgroundThread.IsBackground = true;
          backgroundThread.Start();
         }
}
Lazy Programer
  • 171
  • 1
  • 1
  • 12

3 Answers3

2

You can use backgroundworker class in order to achieve your task

private BackgroundWorker bg1 = new BackgroundWorker();
 bg1.DoWork += bg1_DoWork;

 private void bg1_DoWork(object sender, DoWorkEventArgs e)
        {
           //the function you want to execute
        }
hustlecoder
  • 187
  • 1
  • 1
  • 9
  • Well It seems same like `Thread.Isbackground = true;` i want the result like if i call `string x = getStringResult();` i will get the result inside x if getResult contains code that return a string type. how can i return and assign value to some string after this background worker executes? like `string result = backgroudnworker?Result(); ` – Lazy Programer Dec 22 '17 at 04:51
  • Declare the string in the class(outside the method), then you can manipulate that string through the function in your backgroundWorker – hustlecoder Dec 22 '17 at 05:06
  • There is a RunWorkerCompleted event: [MSDN](https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted(v=vs.110).aspx) – Mátray Márk Dec 22 '17 at 07:44
1

In this case your operation is I/O bound, so an asynchronous approach is best. To do this you can use the async keyword on your events.

private async void getDataFrmUrlButton_Click(object sender, EventArgs args)
{
    using(var client = new WebClient())
    {
        string result = await client.DownloadStringTaskAsync(uri);

        // Do stuff with data
    }
}

This post gives some good resources for more information on async/await.

burnttoast11
  • 1,164
  • 16
  • 33
  • Correct, no need to explicitly create a new Thread. By using `async/await` your main thread will regain control while the application waits for the response. Behinds the scenes it will send an event when the data is ready and continue running your method. – burnttoast11 Dec 22 '17 at 05:08
  • Okay! but async methods always void ! is it possible to return string? – Lazy Programer Dec 22 '17 at 05:16
  • You can return data from an `async` method by returning a `Task`. So if you wanted to return a string it would look like this: `private async Task`. But in this case we have `async` on an event, so we have to return `void`. So you would need to do something like @hustlecoder suggested, use a member variable in your class. – burnttoast11 Dec 22 '17 at 05:21
1

If you want a more enterprise based solution you can have a look at Hangfire (https://www.hangfire.io/).

While normally targeted at ASP.NET solutions you can also run it as part of a windows service and use that in conjunction with your WinForm based application(s). It will allow you to easily hand off long running tasks and track them even if you don't want to to use TPL to do it yourself.

TheEdge
  • 9,291
  • 15
  • 67
  • 135