

using System.Threading;

namespace CsvCount_ES
{
    /// <summary>
    /// 一个工作的封装类。
    /// </summary>
    public class WorkItem
    {
        private object result;

        public bool IsCompleted { get; set; }
        /// <summary>
        /// 回调函数
        /// </summary>
        internal ThreadPool.WorkItemCallback Delegate { get; set; }
        public object DelegateInputParameters { get; set; }
        /// <summary>
        /// 工作状态
        /// </summary>
        public WorkItemStateTypeless WorkItemStateTypeless { get; set; }
        /// <summary>
        /// 线程类
        /// </summary>
        public SingleThreadRunner SingleThreadRunner { get; set; }


        public object Result
        {
            get
            {
                // 自旋锁-工作完成
                var spinWait = new SpinWait();
                while (!IsCompleted)
                {
                    spinWait.SpinOnce();
                    Thread.MemoryBarrier();
                }
                return result;
            }
            set { result = value; }
        }

        /// <summary>
        ///  实例 <see cref="WorkItem" /> .
        /// </summary>
        internal WorkItem()
        {
        }

        /// <summary>
        ///     实例化 <see cref="WorkItem" /> .
        /// </summary>
        internal WorkItem(ThreadPool.WorkItemCallback functionDelegate, object delegateInputParameters)
        {
            Delegate = functionDelegate;
            DelegateInputParameters = delegateInputParameters;
            WorkItemStateTypeless = new WorkItemStateTypeless(this);
        }

        /// <summary>
        ///  配置异步回调事件
        /// </summary>
        /// <value></value>
        public ThreadPool.CallbackFunction AsyncCallback { get; set; }
    }
}