C#异步编程的三种⽅式⼀、通过委托实现异步
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()
{
await和async使用方法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"这是返回值";
});
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。