以下是使用 C# 实现同步和异步的代码示例:1. 使用线程实现同步和异步
同步示例:
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("同步操作结束...");
}
}
异步示例:
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. 使用 Task 和 async/await 实现异步
异步示例:
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. 使用委托和回调函数实现异步
异步示例:
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 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);
}
}
以上是使用 C# 实现同步和异步的几种方式,需要根据具体情况选择合适的方法。