static async Task Main()
{
await What();
}
static Task What()
{
return new Task(
() => Console.WriteLine("1"));
}
await Task.Run
(
() => DoExpensiveOperation(someParameter)
);
static async Task Main()
{
Task t = What();
await t;
var s = t.Status;
}
static Task What()
{
return new Task(
() => Console.WriteLine("1"));
}
static Task<int> M1()
{
return Task.FromResult(1);
}
static async Task<int> M2()
{
return await M1();
}
public async Task<string> GetWithKeywordsAsync(string url)
{
using (var client = new HttpClient())
return await client.GetStringAsync(url);
}
public Task<string> GetElidingKeywordsAsync(string url)
{
using (var client = new HttpClient())
return client.GetStringAsync(url);
}
static async Task Main()
{
Task<string> t =
File.ReadAllTextAsync(@"D:\numbers2.txt");
await t;
await t;
await t;
await t;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
int number1 = int.Parse(txtNumber1.Text);
int number2 = int.Parse(txtNumber2.Text);
int result = 0;
Thread.Sleep(4000);
result = number1 + number2;
MessageBox.Show(result.ToString());
}
private async Task Calculate(int number1, int number2)
{
return await Task.Run(() =>
{
Thread.Sleep(4000);
return number1 + number2;
});
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
int number1 = int.Parse(txtNumber1.Text);
int number2 = int.Parse(txtNumber2.Text);
int result = await Calculate(number1, number2);
MessageBox.Show(result.ToString(CultureInfo.InvariantCulture));
}
public class SychronizationContext
{
public virtual void Post(SendOrPostCallback d, Object state)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(d), state);
}
}
public class SychronizationContext
{
public virtual void Send(SendOrPostCallback d, Object state)
{
d(state);
}
}
public sealed class WindowsFormsSynchronizationContext : SynchronizationContext, IDisposable
{
public override void Post(SendOrPostCallback d, Object state) {
if (controlToSendTo != null) {
controlToSendTo.BeginInvoke(d, new object[] { state });
}
}
public override SynchronizationContext CreateCopy() {
return new WindowsFormsSynchronizationContext(controlToSendTo, DestinationThread);
}
}
public sealed class WindowsFormsSynchronizationContext : SynchronizationContext, IDisposable
{
public override void Send(SendOrPostCallback d, Object state) {
Thread destinationThread = DestinationThread;
if (destinationThread == null || !destinationThread.IsAlive) {
throw new InvalidAsynchronousStateException(SR.GetString(SR.ThreadNoLongerValid));
}
if (controlToSendTo != null) {
controlToSendTo.Invoke(d, new object[] { state });
}
}
}
public sealed class DispatcherSynchronizationContext : SynchronizationContext
{
/// <summary>
/// Asynchronously invoke the callback in the SynchronizationContext.
/// </summary>
public override void Post(SendOrPostCallback d, Object state)
{
// Call BeginInvoke with the cached priority. Note that BeginInvoke
// preserves the behavior of passing exceptions to
// Dispatcher.UnhandledException unlike InvokeAsync. This is
// desireable because there is no way to await the call to Post, so
// exceptions are hard to observe.
_dispatcher.BeginInvoke(_priority, d, state);
}
}
public sealed class DispatcherSynchronizationContext : SynchronizationContext
{
/// <summary>
/// Synchronously invoke the callback in the SynchronizationContext.
/// </summary>
public override void Send(SendOrPostCallback d, Object state)
{
// Call the Invoke overload that preserves the behavior of passing
// exceptions to Dispatcher.UnhandledException.
if(BaseCompatibilityPreferences.GetInlineDispatcherSynchronizationContextSend()
&& _dispatcher.CheckAccess())
{
// Same-thread, use send priority to avoid any reentrancy.
_dispatcher.Invoke(DispatcherPriority.Send, d, state);
}
else
{
// Cross-thread, use the cached priority.
_dispatcher.Invoke(_priority, d, state);
}
}
}
private HttpClient _client = new HttpClient();
async Task<List<string>> GetBothAsync(string url1, string url2)
{
var result = new List<string>();
var task1 = GetOneAsync(result, url1);
var task2 = GetOneAsync(result, url2);
await Task.WhenAll(task1, task2);
return result;
}
async Task GetOneAsync(List<string> result, string url)
{
var data = await _client.GetStringAsync(url);
result.Add(data);
}
public static void DoWork()
{
//W wątku UI
var sc = SynchronizationContext.Current;
ThreadPool.QueueUserWorkItem(delegate
{
// zrób coś w ThreadPool w innym wątku
sc.Post(delegate
{
// zrób prace na wątku (UI)
}, null);
});
}
await LetsDoSomethingAsync();
ContinueWithRestOfThisCode();
var task = LetsDoSomethingAsync();
var currentSyncContext = SynchronizationContext.Current;
task.ContinueWith(delegate
{
if (currentSyncContext == null) ContinueWithRestOfThisCode();
else currentSyncContext.Post(delegate { ContinueWithRestOfThisCode(); }, null);
}, TaskScheduler.Current);
var task = LetsDoSomethingAsync();
var currentSyncContext = SynchronizationContext.Current;
task.ContinueWith(delegate
{
if (currentSyncContext == null) ContinueWithRestOfThisCode();
else currentSyncContext.Post(delegate { ContinueWithRestOfThisCode(); }, null);
}, TaskScheduler.Current);
private async void Button_Click(object sender, RoutedEventArgs e)
{
var i = await LetsDoSomethingAsync();
ContinueWithRestOfThisCode(i);
}
private Task LetsDoSomethingAsync()
{
Task.Delay(1000);
return Task.FromResult(1);
}
private void ContinueWithRestOfThisCode(int i)
{
ResultTextBlock.Text = i.ToString();
}
public partial class MainWindow : Window
{
private HttpClient HttpClient = new HttpClient();
private void Button_Click(object sender, RoutedEventArgs e)
{
var result = HttpClient.GetStringAsync("https://postman-echo.com/delay/10").Result;
ResultTextBlock.Text = result;
}
public MainWindow()
{
InitializeComponent();
}
}
public partial class MainWindow : Window
{
private HttpClient HttpClient = new HttpClient();
private async void Button_Click(object sender, RoutedEventArgs e)
{
var result = await HttpClient.GetStringAsync("https://postman-echo.com/delay/10");
ResultTextBlock.Text = result;
}
public MainWindow()
{
InitializeComponent();
}
}
private readonly static string _url = "https://postman-echo.com/delay/10";
private void Button_Click(object sender, RoutedEventArgs e)
{
ResultTextBlock.Text = "";
ResultTextBlock.Text += "Przed MyGetStringAsync()";
var result = MyGetStringAsync().Result;
ResultTextBlock.Text += "Napisze coś w międzyczasie";
ResultTextBlock.Text = result;
ResultTextBlock.Text += "Po MyGetStringAsync()";
}
public async Task<string> MyGetStringAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return await httpClient.GetStringAsync(_url);
}
}
await LetsDoSomethingAsync();
ContinueWithRestOfThisCode();
private void Button_Click(object sender, RoutedEventArgs e)
{
ResultTextBlock.Text = "";
ResultTextBlock.Text += "Przed MyGetStringAsync()";
var result = MyGetStringAsync().Result;
ResultTextBlock.Text += "Napisze coś w międzyczasie";
ResultTextBlock.Text = result;
ResultTextBlock.Text += "Po MyGetStringAsync()";
}
public async Task<string> MyGetStringAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return await httpClient.GetStringAsync(_url)
.ConfigureAwait(false);
}
}
public class ExampleController : Controller
{
public string Get()
{
MyProxy proxy = new MyProxy();
var r = proxy.MyGetStringAsync(
new Uri("https://postman-echo.com/get")).Result;
return r;
}
}
public class MyProxy
{
public async Task<string> MyGetStringAsync(Uri uri)
{
using (var client = new HttpClient())
{
var value = await client.GetStringAsync(uri)
.ConfigureAwait(false);
return value;
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string result = "";
using (HttpClient httpClient = new HttpClient())
{
result = await httpClient.GetStringAsync(_url)
.ConfigureAwait(false);
}
ResultTextBlock.Text = result;
//BUM
}
private readonly static string _url = "https://postman-echo.com/delay/2";
private async void Button_Click(object sender, RoutedEventArgs e)
{
string result = "";
using (HttpClient httpClient = new HttpClient())
{
result = await httpClient.GetStringAsync(_url)
.ConfigureAwait(false);
}
ResultTextBlock.Text = result;
//BUM
}
private readonly static string _url = "https://postman-echo.com/delay/2";
var task = LetsDoSomethingAsync();
var currentSyncContext = SynchronizationContext.Current;
task.ContinueWith(delegate
{
if (currentSyncContext == null) ContinueWithRestOfThisCode();
else currentSyncContext.Post(delegate { ContinueWithRestOfThisCode(); }, null);
}, TaskScheduler.Current);
string result = "";
using (HttpClient httpClient = new HttpClient())
{
result = await httpClient.GetStringAsync(_url)
.ContinueWith(pageHtml =>
{
//Twoj kod UI
return pageHtml.Result;
}
,TaskScheduler.FromCurrentSynchronizationContext());
}
SynchronizationContext synchronizationContext =
SynchronizationContext.Current;
string result = "";
using (HttpClient httpClient = new HttpClient())
{
result = await httpClient.GetStringAsync(_url)
.ContinueWith(pageHtml =>
{
synchronizationContext.Post(__ => {
//Twoj kod UI
}, null);
return pageHtml.Result;
});
}
public void Do(Action job, Action onDone)
{
SynchronizationContext sc = SynchronizationContext.Current;
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
job();
}
finally
{
sc.Post(__ => onDone(), null);
}
});
}
Task.Run(async delegate
{
SynchronizationContext.SetSynchronizationContext
(new MySynchronizationContext());
await MyGetStringAsync();
});
public class MySynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
Console.WriteLine("Sychronizacja się wykonuje");
base.Post(d, state);
}
}
var cesp =
new ConcurrentExclusiveSchedulerPair();
var cesp = new ConcurrentExclusiveSchedulerPair();
Task.Factory.StartNew(() =>
{
Console.WriteLine(TaskScheduler.Current == cesp.ExclusiveScheduler);
}, default, TaskCreationOptions.None,
cesp.ExclusiveScheduler).Wait();
var cesp = new ConcurrentExclusiveSchedulerPair();
var con = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 8)
.ConcurrentScheduler;
var exc = new ConcurrentExclusiveSchedulerPair(con).ExclusiveScheduler;
string result = "";
using (HttpClient httpClient = new HttpClient())
{
result = await httpClient.GetStringAsync(_url)
.ContinueWith(pageHtml =>
{
//Twoj kod UI
return pageHtml.Result;
}
,TaskScheduler.FromCurrentSynchronizationContext());
}
ThreadPool.UnsafeQueueUserWorkItem
TaskAwaiter awaiter = task.GetAwaiter();
static async Task Main()
{
int a = await RandomNumberAsync();
}
private static Task RandomNumberAsync()
{
return Task.FromResult(4);
}
static async Task Main()
{
Task<int> awaitableType = RandomNumberAsync();
var awaiter = awaitableType.GetAwaiter();
if (!awaiter.IsCompleted)
{
//robisz operacje która nie jest związana
//z zakończeniem tego zadania
//coś może działać w tle
//To symulje kod przed wyrażeniem await
}
int a = awaiter.GetResult();
//kod po await
//ten kod jest synchroniczny gdyż nie jest on pakowany przez maszynę stanów
}
private static Task<int> RandomNumberAsync()
{
return Task.FromResult(4);
}
Task<int> awaitableType = RandomNumberAsync();
var awaiter = awaitableType.GetAwaiter();
awaiter.OnCompleted(
() => { Console.WriteLine("Koniec"); }
);
TaskAwaiter awaiter = task.GetAwaiter();
public class MyAwaitable
{
public MyAwaiter GetAwaiter() => new MyAwaiter();
}
public class MyAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
Console.WriteLine("Przed OnCompleted");
continuation.Invoke();
Console.WriteLine("Po OnCompleted");
}
public bool IsCompleted
{
get
{
return true;
}
}
public string GetResult()
{
return "Done";
}
}
static async Task Main()
{
var s = await new MyAwaitable();
Console.WriteLine(s);
}
public class MyAwaiter2 : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
Console.WriteLine("Przed OnCompleted");
continuation.Invoke();
Console.WriteLine("Po OnCompleted");
}
private bool _isCompleted = false;
public bool IsCompleted
{
get
{
if (_isCompleted)
return _isCompleted;
Random r = new Random();
var number = r.Next(0, 100);
if (number > 90)
{
_isCompleted = true;
return true;
}
return false;
}
}
public string GetResult()
{
return "Done";
}
}
var awaiter = new MyAwaitable().GetAwaiter();
while (!awaiter.IsCompleted)
{
Console.WriteLine("Czekam!");
Thread.Sleep(500);
}
public class MyAwaiter3 : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
Console.WriteLine("Przed OnCompleted");
continuation.Invoke();
Console.WriteLine("Po OnCompleted");
}
private bool _isCompleted = false;
public bool IsCompleted
{
get
{
return false;
}
}
public string GetResult()
{
Thread.Sleep(4000);
return "Done";
}
}
public string GetResult()
{
Thread.Sleep(4000);
return "Done";
}
public int GetResult()
{
Thread.Sleep(4000);
return 1;
}
public class MyAwaitable4
{
private volatile bool finished;
public bool IsFinished => finished;
public event Action Finished;
public MyAwaitable4(bool finished) => this.finished = finished;
public void TryFinish()
{
if (finished) return;
Random r = new Random();
var number = r.Next(0, 100);
if (number > 95)
{
finished = true;
Finished?.Invoke();
}
}
public MyAwaiter4 GetAwaiter() => new MyAwaiter4(this);
}
public class MyAwaiter4 : INotifyCompletion
{
private readonly MyAwaitable4 awaitable;
private int result;
public MyAwaiter4(MyAwaitable4 awaitable)
{
this.awaitable = awaitable;
if (IsCompleted)
SetResult();
}
public bool IsCompleted => awaitable.IsFinished;
public int GetResult()
{
if (!IsCompleted)
{
//var wait = new SpinWait();
while (!IsCompleted)
{
Console.WriteLine("Czekam SPIN");
awaitable.TryFinish();
//wait.SpinOnce();
Thread.Sleep(100);
}
}
return result;
}
public void OnCompleted(Action continuation)
{
if (IsCompleted)
{
continuation();
return;
}
var capturedContext = SynchronizationContext.Current;
awaitable.Finished += () =>
{
SetResult();
if (capturedContext != null)
capturedContext.Post(_ => continuation(), null);
else
continuation();
};
GetResult();
}
private void SetResult()
{
result = new Random().Next();
}
}
static async Task Main()
{
var a = new MyAwaitable4(false);
var awaiter = a.GetAwaiter();
awaiter.OnCompleted(() => { Console.WriteLine("Dalsza część kodu"); });
var res = awaiter.GetResult();
Console.WriteLine(res);
var b = new MyAwaitable4(false);
var res2 = await b;
//dalsza część kodu (dosłownie)
Console.WriteLine(res2);
}
public void OnCompleted(Action continuation)
{
if (IsCompleted)
{
continuation();
return;
}
var capturedContext = SynchronizationContext.Current;
awaitable.Finished += () =>
{
SetResult();
if (capturedContext != null)
capturedContext.Post(_ => continuation(), null);
else
continuation();
};
GetResult();
}
public int GetResult()
{
if (!IsCompleted)
{
//var wait = new SpinWait();
while (!IsCompleted)
{
Console.WriteLine("Czekam SPIN");
awaitable.TryFinish();
//wait.SpinOnce();
Thread.Sleep(100);
}
}
return result;
}
public void TryFinish()
{
if (finished) return;
Random r = new Random();
var number = r.Next(0, 100);
if (number > 95)
{
finished = true;
Finished?.Invoke();
}
}
public static CultureAwaiter WithCurrentCulture(this Task task)
{
return new CultureAwaiter(task);
}
public class CultureAwaiter : INotifyCompletion
{
private readonly TaskAwaiter m_awaiter;
private CultureInfo m_culture;
public CultureAwaiter(Task task)
{
if (task == null) throw new ArgumentNullException(“task”);
m_awaiter = task.GetAwaiter();
}
public CultureAwaiter GetAwaiter() { return this; }
public bool IsCompleted { get { return m_awaiter.IsCompleted; } }
public void OnCompleted(Action continuation)
{
m_culture = Thread.CurrentThread.CurentCulture;
m_awaiter.OnCompleted(continuation);
}
public void GetResult()
{
if (m_culture != null) Thread.CurrentThread.CurrentCulture = m_culture;
m_awaiter.GetResult();
}
}
public static ControlAwaiter GetAwaiter(this Control control)
{
return new ControlAwaiter(control);
}
public struct ControlAwaiter : INotifyCompletion
{
private readonly Control m_control;
public ControlAwaiter(Control control)
{
m_control = control;
}
public bool IsCompleted
{
get { return !m_control.InvokeRequired; }
}
public void OnCompleted(Action continuation)
{
m_control.BeginInvoke(continuation);
}
public void GetResult() { }
}
public static class TaskAwaiterHelper
{
public static TaskAwaiter GetAwaiter(this TimeSpan timespan)
{
return Task.Delay(timespan).GetAwaiter();
}
public static TaskAwaiter GetAwaiter(this string word)
{
return Task.Delay(word.Length).GetAwaiter();
}
public static TaskAwaiter GetAwaiter(this DateTimeOffset dateTimeOffset)
{
return (dateTimeOffset – DateTimeOffset.UtcNow).GetAwaiter();
}
}
static async Task Main()
{
await TimeSpan.FromSeconds(2);
await "Stefan";
}
static async Task Main()
{
var proces = Process.Start("notepad.exe");
proces.WaitForExit();
var result = proces.ExitCode;
}
public static class TaskAwaiterHelper
{
public static TaskAwaiter<int> GetAwaiter(this Process process)
{
var tsc = new TaskCompletionSource<int>(
TaskCreationOptions.RunContinuationsAsynchronously);
process.EnableRaisingEvents = true;
process.Exited += (sender, args) =>
{
var senderProcess = sender as Process;
if (senderProcess == null)
return;
tsc.SetResult(senderProcess.ExitCode);
};
return tsc.Task.GetAwaiter();
}
}
public static Task PerformOperation(this PictureBox pictureBox)
{
var tcs = new TaskCompletionSource<object>();
// Naive version that does not unsubscribe from the event
pictureBox.LoadCompleted += (s, ea) =>
{
if (ea.Cancelled) tcs.SetCanceled();
else if (ea.Error != null) tcs.SetException(ea.Error);
else tcs.SetResult(null);
};
pictureBox.LoadAsync();
return tcs.Task;
}
static async Task BarAsync()
{
Console.WriteLine("This happens before await");
int i = await QuxAsync();
Console.WriteLine("This happens after await. The result of await is " + i);
}
private static Task BarAsync()
{
Program.<BarAsync>d__2 stateMachine;
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
stateMachine.<>t__builder.Start<Program.<BarAsync>d__2>(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
private struct <BarAsync>d__2 : IAsyncStateMachine
{
public int <>1__state;
public AsyncTaskMethodBuilder <>t__builder;
private TaskAwaiter<int> <>u__1;
void IAsyncStateMachine.MoveNext()
{
int num1 = this.<>1__state;
try
{
TaskAwaiter<int> awaiter;
int num2;
if (num1 != 0)
{
Console.WriteLine("This happens before await");
awaiter = Program.QuxAsync().GetAwaiter();
if (!awaiter.IsCompleted)
{
this.<>1__state = num2 = 0;
this.<>u__1 = awaiter;
this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter<int>, Program.<BarAsync>d__2>(ref awaiter, ref this);
return;
}
}
else
{
awaiter = this.<>u__1;
this.<>u__1 = new TaskAwaiter<int>();
this.<>1__state = num2 = -1;
}
Console.WriteLine("This happens after await. The result of await is " + (object) awaiter.GetResult());
}
catch (Exception ex)
{
this.<>1__state = -2;
this.<>t__builder.SetException(ex);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
{
this.<>t__builder.SetStateMachine(stateMachine);
}
}
public struct YieldAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
ThreadPool.QueueUserWorkItem(new WaitCallback
(
(a) => { continuation(); }
));
}
public bool IsCompleted
{
get
{
return false;
}
}
public void GetResult()
{
}
}
[SecurityCritical]
private static void QueueContinuation(Action continuation, bool flowContext)
{
................
var syncCtx = SynchronizationContext.CurrentNoFlow;
if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext))
{
syncCtx.Post(s_sendOrPostCallbackRunAction, continuation);
}
else
{
TaskScheduler scheduler = TaskScheduler.Current;
if (scheduler == TaskScheduler.Default)
{
if (flowContext)
{
ThreadPool.QueueUserWorkItem(s_waitCallbackRunAction, continuation);
}
else
{
ThreadPool.UnsafeQueueUserWorkItem(s_waitCallbackRunAction, continuation);
}
}
// We're targeting a custom scheduler, so queue a task.
else
{
Task.Factory.StartNew(continuation, default(CancellationToken), TaskCreationOptions.PreferFairness, scheduler);
}
}
}
static async Task Main()
{
await Task.Yield();
//dalszy kod
}
public async void MyButton_Click(object sender, RoutedEventArgs e)
{
for( int i=0; i < 10000; i++)
{
ProcessSomeStuff(i);
// await the Yield to ensure all waiting messages
// are processed before continuing
await Task.Yield();
}
}
async void Form_Load(object s, object e)
{
await Task.Yield();
MessageBox.Show("Async message!");
}
async Task DoUIThreadWorkAsync(CancellationToken token)
{
var i = 0;
while (true)
{
token.ThrowIfCancellationRequested();
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
// do the UI-related work item
this.TextBlock.Text = "iteration " + i++;
}
}
public static Task IdleYield()
{
var idleTcs = new TaskCompletionSource();
// subscribe to Application.Idle
EventHandler handler = null;
handler = (s, e) =>
{
Application.Idle -= handler;
idleTcs.SetResult(true);
};
Application.Idle += handler;
return idleTcs.Task;
}