The following is a code example of synchronous and asynchronous implementation using C#: 1. Synchronous and asynchronous implementation using threads
Synchronous example:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始执行同步操作...");
DoWork();
Console.WriteLine("开始执行其他操作...");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("同步操作开始...");
Thread.Sleep(5000);
Console.WriteLine("同步操作结束...");
}
}
Asynchronous example:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始执行异步操作...");
Thread thread = new Thread(DoWork);
thread.Start();
Console.WriteLine("开始执行其他操作...");
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("异步操作开始...");
Thread.Sleep(5000);
Console.WriteLine("异步操作结束...");
}
}
2. Use Task and async/await to achieve asynchrony
Asynchronous example:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("开始执行异步操作...");
await DoWorkAsync();
Console.WriteLine("开始执行其他操作...");
Console.ReadKey();
}
static async Task DoWorkAsync()
{
Console.WriteLine("异步操作开始...");
await Task.Delay(5000);
Console.WriteLine("异步操作结束...");
}
}
3. Use delegates and callback functions to achieve asynchrony
Asynchronous example:
using System;
using System.Threading;
class Program
{
delegate void Callback();
static void Main(string[] args)
{
Console.WriteLine("开始执行异步操作...");
Callback callback = DoWork;
IAsyncResult result = callback.BeginInvoke(null, null);
Console.WriteLine("开始执行其他操作...");
callback.EndInvoke(result);
Console.ReadKey();
}
static void DoWork()
{
Console.WriteLine("异步操作开始...");
Thread.Sleep(5000);
Console.WriteLine("异步操作结束...");
}
}
4. Using events to achieve asynchrony
Asynchronous example:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始执行异步操作...");
Worker worker = new Worker();
worker.Completed += Worker_Completed;
worker.DoWorkAsync();
Console.WriteLine("开始执行其他操作...");
Console.ReadKey();
}
static void Worker_Completed(object sender, EventArgs e)
{
Console.WriteLine("异步操作结束...");
}
}
class Worker
{
public event EventHandler Completed;
public void DoWorkAsync()
{
Thread thread = new Thread(DoWork);
thread.Start();
}
void DoWork()
{
Console.WriteLine("异步操作开始...");
Thread.Sleep(5000);
Completed(this, EventArgs.Empty);
}
}
The above are several ways to implement synchronous and asynchronous using C#, and you need to choose the appropriate method according to the specific situation.