一、通過委托實作異步
namespace Test1
{
class AsyncDemo
{
public void async()
{
string i = "引數";
Console.WriteLine("呼叫異步方法前");
PostAsync(i);
Console.WriteLine("呼叫異步方法后");
}
delegate void AsyncFoo(string i);
private static void PostAsync(object o)
{
AsyncFoo caller = Myfunc;
caller.BeginInvoke(o.ToString(), FooCallBack, caller);
}
private static void FooCallBack(IAsyncResult ar)
{
var caller = (AsyncFoo)ar.AsyncState;
caller.EndInvoke(ar);
}
private static void Myfunc(string i)
{
Console.WriteLine("通過委托來實作異步編程的");
}
}
}
二、通過Task實作
namespace Test1
{
class TaskDemo
{
public void taskDemo()
{
Console.WriteLine("主執行緒,執行緒ID:"+Thread.CurrentThread.ManagedThreadId);
//Task方式1
Task task1= new Task(()=>TaskFunc1());
task1.Start();
//Task方式2
var result = Task.Run<string>(()=>{ return TaskFunc2(); });
Console.WriteLine(result.Result);
}
private static void TaskFunc1()
{
Console.WriteLine("Task方式1開啟的執行緒ID:"+Thread.CurrentThread.ManagedThreadId);
for(int i = 0; i < 100; i++)
{
Console.WriteLine(i);
}
}
private static string TaskFunc2()
{
for (int i = 100; i < 200; i++)
{
Console.WriteLine(i);
}
return "Task方式2開啟的執行緒ID:"+ Thread.CurrentThread.ManagedThreadId;
}
}
}
三、通過await async實作
namespace Test1
{
class awaitAsyncDemo
{
public void Demo()
{
Console.WriteLine("主執行緒,執行緒ID:" + Thread.CurrentThread.ManagedThreadId);
var result = AsyncFunc();
Console.WriteLine(result.Result);
}
private static async Task<string> AsyncFunc()
{
return await Task.Run(() =>
{
Console.WriteLine("await/async的執行緒ID:"+Thread.CurrentThread.ManagedThreadId);
return "這是回傳值";
});
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/236675.html
標籤:其他
上一篇:互聯網直播點播智能分析平臺EasyDSS如何實作對制定目錄系結或解綁用戶?
下一篇:Windows/Android平臺視頻同屏功能組件EasyScreenLive-Win如何設定螢屏采集是否采集滑鼠游標?
