简体   繁体   中英

C# Tasks get result or catch exception

I have:

public static async Task<string> httpRequest(HttpWebRequest request)

I would like to do this:

string rez1;
static void test()
    {
        Task.Factory.StartNew(() => { 
            //How can I get result like rez1= httpRequest((HttpWebRequest)HttpWebRequest.Create("google.com")));
            //or catch WebException here.
        });
    }

How can I do it? Thanks

You have it mixed up a little bit. When your methods signature is:

public static async Task<string> httpRequest(HttpWebRequest request)

That means "this method is invoked asynchronously, i will call it and it will return imminently with a promise to finish in the future".

You should change your method to look like this:

Edit

Fixed the code according to the comments made.

public static Task<string> httpRequest(HttpWebRequest request)
{
  return Task.Factory.Startnew(() = > {
      return HttpWebRequest.Create("google.com")
  }
}

When your method is marked as async, that means the caller might think it is "pure" async, which means no threads execute behind the scenes. If you do fire up a new thread (as you are doing here, by using a Thread Pool thread) you should explicitly comment your method and tell your invoker that he will be firing up a new thread.

You can save yourself firing up a new Task if you're using .NET 4.5 and have access to the new HttpClient class.

You can change your method to look like this:

public static async Task<string> httpRequest(HttpWebRequest request)
{
  var httpClient = new HttpClient();
  var response = await httpClient.GetAsync("http://www.google.com")
  var stringResult = await response.Content.ReadAsStringAsync();

  return stringResult;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM