C#代碼延時的幾種實現(xiàn)
更新時間:2021年08月04日 11:28:34 作者:陳言必行
本文主要介紹了C#代碼延時的幾種實現(xiàn),主要介紹了三種方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
Task.Delay();異步實現(xiàn)
using System;
using System.Threading.Tasks;
namespace csharpYS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Mian方法第一次輸出...");
#region 第一種形式
var task_1 = Task.Run(async delegate
{
await Task.Delay(3000);
Console.WriteLine("3秒后執(zhí)行,方式一 輸出語句...");
return "異步執(zhí)行result"; //可以得到一個返回值(int,bool,string都試了)
});
#endregion
Console.WriteLine("Mian方法第二次輸出,調(diào)用延時...");
Console.WriteLine("task_1 的 Status:{0}, 結(jié)果: {1}",task_1.Status, task_1.Result);
Console.WriteLine("第一種形式,延時結(jié)束...");
#region 第二種形式
Task task_2 = Task.Run(task_YS);
//task_2.Wait(); //注釋打開則等待task_2延時,注釋掉則不等待
#endregion
Console.WriteLine("Mian方法最后一次輸出,Main方法結(jié)束...");
Console.ReadKey();
}
public static async Task task_YS()
{
await Task.Delay(5000);
Console.WriteLine("5秒后執(zhí)行,方式二 輸出語句...");
}
}
}
下圖一為注釋運行結(jié)果,圖二為注釋打開運行結(jié)果:(建議使用時自行實踐)


覺得上面方法不適用的童鞋,可以試試使用線程的方式:
線程實現(xiàn):
簡例:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace ExceptionDeme
{
class ThreadDemo
{
static void Main(string[] args)
{
Console.WriteLine("Main方法開始執(zhí)行...");
Thread threadA = new Thread(DownLoadFile);
threadA.Start();
Console.WriteLine("Main方法執(zhí)行結(jié)束...");
Console.ReadKey();
}
static void DownLoadFile()
{
//模擬開始下載 2S 后完成
Console.WriteLine("開始下載,此協(xié)程的Id是:" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.WriteLine("下載完成");
}
}

相關連接:
C# 線程簡介
C# 開啟線程的幾種方式
計時器方式實現(xiàn):
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Czhenya ... Main Start");
WaitFunctions(2);
Console.WriteLine("Czhenya ... Main End");
}
public static void WaitFunctions(int waitTime)
{
if (waitTime <= 0) return;
Console.WriteLine("開始執(zhí)行 ...");
DateTime nowTimer = DateTime.Now;
int interval = 0;
while (interval < waitTime)
{
TimeSpan spand = DateTime.Now - nowTimer;
interval = spand.Seconds;
}
Console.WriteLine(waitTime + "秒后繼續(xù) ...");
}
}
執(zhí)行截圖:

到此這篇關于C#代碼延時的幾種實現(xiàn)的文章就介紹到這了,更多相關C# 代碼延時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
c# socket網(wǎng)絡編程接收發(fā)送數(shù)據(jù)示例代碼
這篇文章主要介紹了c# socket網(wǎng)絡編程,server端接收,client端發(fā)送數(shù)據(jù),大家參考使用吧2013-12-12
C#查詢SqlServer數(shù)據(jù)庫并返回單個值的方法
這篇文章主要介紹了C#查詢SqlServer數(shù)據(jù)庫并返回單個值的方法,涉及C#操作SQLServer數(shù)據(jù)庫查詢的相關技巧,需要的朋友可以參考下2015-06-06

