1. 程式人生 > >C# 安全回撥的非同步處理的封裝

C# 安全回撥的非同步處理的封裝

 在視窗 load 裡呼叫 AsyncTask.InitUIContext(); 初始化同步上下文

SwitchToUI  可以在多執行緒裡切換到UI執行緒執行委託程式碼

AsyncSend  以阻塞模式執行回撥

AsyncPost  以非阻塞模式執行回撥

AsyncTask.AsyncPost<String>(() =>
{
    //在新的執行緒裡執行
    return 獲取網站原始碼?();
}, (v) =>
{
    //回到UI執行緒執行
    TextBox1.Text = v;
});

using System;
using System.Threading;

namespace Wpf.Domain
{
    /// <summary>
    /// 非同步任務 UI執行緒回撥相關
    /// </summary>
    public static class AsyncTask
    {
        private static SynchronizationContext Context { get; set; }
        /// <summary>
        /// 初始化UI執行緒(只能在UI執行緒裡初始化)
        /// </summary>
        public static void InitUIContext()
        {
            Context = SynchronizationContext.Current;
        }

        /// <summary>
        /// 切換到UI執行緒執行委託
        /// </summary>
        /// <param name="callback"></param>
        public static void SwitchToUI(Action callback)
        {
            try
            {
                if (SynchronizationContext.Current == Context)
                {
                    callback();
                }
                else
                {
                    Context.Send((s) =>
                    {
                        callback();
                    }, null);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("AsyncTask.SwitchToUI=>" + ex.Message, ex);
            }
        }



        /// <summary>
        /// 非同步執行委託,在完成後Send回撥UI執行緒
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="asyncfunc">非同步執行</param>
        /// <param name="completecallback">執行完成後回到當前執行緒回撥</param>
        public static void AsyncSend<T>(Func<T> asyncfunc,Action<T> completecallback)
        {
            ThreadPool.QueueUserWorkItem((e) =>
            {
                try
                {
                    var result = asyncfunc();
                   
                    Context.Send((s) =>
                    {
                        completecallback((T)s);
                    }, result);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("AsyncTask.Async=>" + ex.Message, ex);
                }
            });
        }

        /// <summary>
        /// 非同步執行委託,在完成後Post回撥UI執行緒
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="asyncfunc">要非同步執行的程式碼</param>
        /// <param name="completecallback">完成後Post執行的程式碼</param>
        public static void AsyncPost<T>(Func<T> asyncfunc, Action<T> completecallback)
        {
            ThreadPool.QueueUserWorkItem((e) =>
            {
                try
                {
                    var result = asyncfunc();

                    Context.Post((s) =>
                    {
                        completecallback((T)s);
                    }, result);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("AsyncTask.Async=>" + ex.Message, ex);
                }
            });
        }

    }
}