using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApp24
{
class Program : System.Windows.Forms.Form
{
EventHandler eventHandler;
public Program() {
eventHandler = OnClick1;
lb1 = new Label();
lb1.Text = "fff";
button1 = new Button();
button1.Location = new System.Drawing.Point(100, 100);
button1.Text = "addd";
button1.Click += eventHandler;
this.Controls.Add(lb1);
this.Controls.Add(button1);
}
void OnClick1(object sender, EventArgs e)
{
OnStartAsynConfigureAwait();
lb1.Text = "变";
}
private Button button1;
private Label lb1;
void main5()
{
//OnStartAsync();
OnStartAsynConfigureAwait();
}
async void OnStartAsync()
{
play($"Ui thread:{GetThread()}");
await Task.Delay(1000);
play($"after thread:{GetThread()}");
}
void play(string str)
{
Console.WriteLine(str);
}
string GetThread() => $"thread:{Environment.CurrentManagedThreadId}";
async void OnStartAsynConfigureAwait()
{
play($"Ui thread:{GetThread()}");
string s = await AsyncFunction().ConfigureAwait(continueOnCapturedContext: true);
play($"{s}");
play($"after thread:{GetThread()}");
}
async Task<string> AsyncFunction()
{
string result = $"\nasync function:{GetThread()}";
await Task.Delay(1000).ConfigureAwait(continueOnCapturedContext: false);
result += $"\nasync function after:{GetThread()}";
return result;
}
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("ddd");
Application.Run(new Program());
Console.ReadLine();
}
}
}
OnStartAsynConfigureAwait == 函数1
AsyncFunction == 函数2
线程判断条件 | 线程判断结果 | ||||
同步上下文 | 开始 | 结束 | |||
函数1 | 函数2 | 函数1 | 函数2 | 函数1 | 函数2 |
true | true | 1 | 1 | 1 | 1 |
true | false | 1 | 1 | 4 | 1 |
false | true | 1 | 1 | 1 | 4 |
false | false | 1 | 1 | 4 | 4 |
- | - | 1 | 1 | 1 | 1 |