zgrkpnr89
zgrkpnr89

Reputation: 335

Why does not HttpClient work in BackgroundWorker?

Here is the code

static BackgroundWorker worker = new BackgroundWorker();

static void Main(string[] args)
{

    worker.DoWork += worker_DoWork;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.RunWorkerAsync();
    Console.ReadLine();
}

static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Console.WriteLine(e.Result);
}

public static async void worker_DoWork(object sender, DoWorkEventArgs e)
{
    var client = new HttpClient();

    string httpResult = await client.GetStringAsync("http://ozgurakpinar.net/androidserver.aspx?param=accenture2");
    e.Result = httpResult;
}

It waits forever in GetStringAsync line. However it works when I use thread instead of BackgroundWorker.

Upvotes: 1

Views: 1520

Answers (1)

usr
usr

Reputation: 171246

Your misunderstandings:

  1. async void returns immediately causing BackgroundWorker to think the work is done. BackgroundWorker is obsolete with await. Delete all of that.
  2. BackgroundWorker makes no sense in a console application. It is a component made for UIs.

It's actually quite simple when you throw out all the unneeded stuff:

static void Main(string[] args)
{
    Console.ReadLine(worker_DoWork().Result); //intentionally blocking here
}

static async Task<string> worker_DoWork()
{
    var client = new HttpClient();

    string httpResult = await client.GetStringAsync("http://ozgurakpinar.net/androidserver.aspx?param=accenture2");
    return httpResult;
}

Async and threading are dangerous tools. Use when required, not by default.

Upvotes: 3

Related Questions