1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RestSharp.Portable: Task<IRestResponse>をWait()できないのでTaskでラップする

Posted at

URIをRestSharpでGETする:


		public Task<IRestResponse> AsyncRestSharp(string uri)
		{
			var client = new RestClient (uri);
			var req = new RestRequest ("/", HttpMethod.Get);
			var res =  client.Execute (req);

			return res;
		}

TaskをWait()するとメインスレッドが止まってしまうダメな例(iOS):

		
		[Test]
		public void TestRestSharpWithTask()
		{
           var call = AsyncRestSharp ("http://www.google.com");
			call.Wait ();
			Console.WriteLine( call.result.RawBytes.ToUtf8() );

		}		

さらに非同期TaskでラップしてWaitすると行ける


		[Test]
		public void TestRestSharpWithTask()
		{

			var tcs = new TaskCompletionSource<string>();
			Task.Run (async () => {
				var res = await AsyncRestSharp("http://www.google.com");
				tcs.SetResult( res.RawBytes.ToUtf8());
			});
			tcs.Task.Wait();

			Console.WriteLine (tcs.Task.Result);
		}		

ちなみにToUtf8():


	public static class Extensions
	{
		public static string ToUtf8(this byte[] src )
		{
			return System.Text.Encoding.UTF8.GetString (src);
		}
	}

もうちょいコーディグが楽になるようなディレクティブとかできないかな。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?