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

UI線程同步

系統 1956 0

WINFORM開發(fā)中常用的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元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 明水县| 庄河市| 久治县| 枝江市| 盖州市| 昭觉县| 小金县| 雅江县| 大新县| 枣庄市| 当涂县| 佛学| 马山县| 新蔡县| 唐山市| 三原县| 神池县| 和硕县| 松滋市| 娱乐| 长葛市| 彭山县| 双城市| 白玉县| 泾源县| 疏附县| 承德市| 焦作市| 高安市| 昆山市| 庆元县| 康平县| 宁武县| 合阳县| 雅安市| 泰州市| 响水县| 麻江县| 闽清县| 石河子市| 湘潭市|