常用代码之二:使用BackgroundWorker或Task让代码异步执行。

先要引用System.ComponentModel

using System.ComponentModel;

然后创建backgroundworker

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            TestArgs args = (TestArgs)e.Argument;
            MyMethod(args.Content, args.Index);
        }

        /// <summary>
        /// backgroundWorker1_DoWork事件使用的参数类
        /// </summary>
        protected class TestArgs
        {
            public string Content { set; get; }
            public int Index { set; get; }

            public TestArgss(string content, int index)
            {
                Content = content;
                Index = index;
            }
        }

        public void BulkFillJson(string content, int index)
        {
            BackgroundWorker backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;

            TestArgsargs = new TestArgs(content, index);

            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);

            backgroundWorker1.RunWorkerAsync(args);
        }

如果使用.net 4.0并行库中的task,则更简单了,一段就搞定,性能还更高。

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                MyMethod(content, index);
            });
原文地址:https://www.cnblogs.com/liuzhendong/p/3370989.html