Skip to content

Instantly share code, notes, and snippets.

@rolfbjarne
Created March 7, 2024 13:15
Show Gist options
  • Save rolfbjarne/e415f1bc4ca9b98964041c28a37ad311 to your computer and use it in GitHub Desktop.
Save rolfbjarne/e415f1bc4ca9b98964041c28a37ad311 to your computer and use it in GitHub Desktop.
using System.Net.Http.Headers;
namespace http_test;
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
public override UIWindow? Window
{
get;
set;
}
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// create a new window instance based on the screen size
Window = new UIWindow(UIScreen.MainScreen.Bounds);
// create a UIViewController with a single UILabel
var vc = new UIViewController();
vc.View!.AddSubview(new UILabel(Window!.Frame)
{
BackgroundColor = UIColor.SystemBackground,
TextAlignment = UITextAlignment.Center,
Text = "Hello, iOS!",
AutoresizingMask = UIViewAutoresizing.All,
});
Window.RootViewController = vc;
// make the window visible
Window.MakeKeyAndVisible();
const int count = 100;
var rnd = new Random ();
var tasks = new Task[count];
var str = new string ('z', 1024 * 1024 * 100); // 100 mb
var content = new StringContent (str);
for (var i = 0; i < count; i++) {
tasks [i] = SendRequest(i, content, TimeSpan.FromSeconds (rnd.NextDouble () * 10));
}
Task.WaitAll (tasks);
Console.WriteLine ("All done");
return true;
}
HttpClient httpClient = new();
async Task SendRequest(int id, HttpContent content, TimeSpan cancellationDelay)
{
try
{
var url = "https://httpbin.org/delay/10";
Console.WriteLine ($"{id} Sending to {url}, waiting {cancellationDelay.TotalSeconds:#.##} s before cancelling");
var requestMessage = new HttpRequestMessage (HttpMethod.Post, url) { Content = content };
var token = new CancellationTokenSource ();
var task = httpClient.SendAsync(requestMessage, token.Token).ConfigureAwait (false);
var ignore = Task.Delay (cancellationDelay).ContinueWith (v =>
{
token.Cancel ();
});
var response = await task;
if (response.IsSuccessStatusCode) {
Console.WriteLine ($"{id} Success");
return;
}
Console.WriteLine ($"{id} ❌ response failed: {response.StatusCode}");
Console.WriteLine (await response.Content.ReadAsStringAsync().ConfigureAwait(false));
} catch (TaskCanceledException e) {
Console.WriteLine ($"{id} ⚠️ {e.Message}");
} catch (Exception e) {
Console.WriteLine ($"{id} ❌ {e.Message}");
Console.WriteLine ($"{id} {e.StackTrace}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment