C# .NET Framework 4.0 异步

.NET Framework 4.0 只能用Task.Factory.StartNew() 4.0以上的则可以直接使用Task.Run()。

Task.Factory.StartNew(() =>{})

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace com._80community.unittest
{
    [TestClass]
    public class UnitTestAsyncAndAwait
    {
        [TestMethod]
        public void TestMethod1()
        {
            var result = DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
            var result1 = Test1().Result;
            var result2 = Test2().Result;

        }

        public async Task<string> Test1()
        {
            var temp = Task.Run(() =>
            {
                Thread.Sleep(5000);
                return DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
            });

            return await temp;
        }
        public async Task<string> Test2()
        {
            var temp2 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                return DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
            });

            return await temp2;
        }
    }
}

  

posted @ 2024-06-15 23:15  Dsw  阅读(102)  评论(0编辑  收藏  举报