日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

UI線程同步

系統 1927 0

WINFORM開發中常用的UI線程同步相關代碼

      
        using
      
       System;
      
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadTestApp
{

/// <summary>
/// 線程同步測試
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnInvoke_Click( object sender, EventArgs e)
{
// 1.直接調用
OperateUI(DoSomeThing( " 直接調用 " ));

// 2.同步器調用
var v2 = new Task< string >(() => DoSomeThing( " 同步器調用 " ));
v2.Start();
v2.ContinueWith((o) => { OperateUI(o.Result); }, CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

// 3.異步異常捕捉
var v3 = new Task< string >(() => DoSomeThing( " ThrowEx " ));
v3.Start();
v3.ContinueWith((o) => { OperateUI(v3.Exception.InnerExceptions[ 0 ].Message); }, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

// 4.經典UI調用
ThreadPool.QueueUserWorkItem((o) => { Classic(DoSomeThing( " 經典UI調用 " )); });

}

private void Classic( string v)
{
if ( this .InvokeRequired) // 需要找到一個調用控件
{
Action< string > a = new Action< string >(OperateUI);
this .Invoke(a, new object [] { v });
}
else
{
OperateUI(v);
}
}

private void OperateUI( string v)
{

tabDisplay.TabPages.Add(v);

lblDisplay.Text = v;

MessageBox.Show(v);

this .Text = v;
}



private string DoSomeThing( string v)
{
if (v == " ThrowEx " )
throw new Exception( " 自定義異常 " );

else
return " [ " + v + " ] " ;
}

}
}



UI線程同步


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 柘荣县| 崇信县| 白玉县| 思南县| 家居| 商丘市| 龙陵县| 龙川县| 伊金霍洛旗| 湖北省| 喀喇| 南阳市| 马尔康县| 象山县| 夏邑县| 曲水县| 葫芦岛市| 中山市| 罗定市| 汝城县| 梓潼县| 临沧市| 台北县| 房产| 门头沟区| 河北省| 靖边县| 揭阳市| 华容县| 本溪市| 吴忠市| 巴楚县| 临邑县| 莲花县| 贡山| 巴东县| 闻喜县| 昌宁县| 象山县| 监利县| 凉山|