c# - 异步编程-同步上下文

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
truetrue1111
truefalse1141
falsetrue1114
falsefalse1144
--1111

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值