面试题答案
一键面试缓存机制
- 页面缓存:在ASP.NET中,可以使用
@ OutputCache
指令对整个页面进行缓存。例如:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
这将缓存页面60秒,期间相同请求直接从缓存返回,无需重新执行页面代码。
2. 数据缓存:使用System.Web.Caching.Cache
对象来缓存经常访问的数据。比如:
public static object GetCachedData(string key)
{
return HttpContext.Current.Cache[key];
}
public static void SetCachedData(string key, object data, int cacheDuration)
{
HttpContext.Current.Cache.Insert(key, data, null,
DateTime.Now.AddMinutes(cacheDuration), Cache.NoSlidingExpiration);
}
- 分布式缓存:对于大规模高并发应用,可以引入分布式缓存,如Redis。在C#中使用StackExchange.Redis库,示例代码如下:
using StackExchange.Redis;
public class RedisCacheHelper
{
private static ConnectionMultiplexer _redis;
private static IDatabase _database;
static RedisCacheHelper()
{
_redis = ConnectionMultiplexer.Connect("localhost:6379");
_database = _redis.GetDatabase();
}
public static string GetString(string key)
{
return _database.StringGet(key);
}
public static void SetString(string key, string value)
{
_database.StringSet(key, value);
}
}
数据库连接管理
- 连接池:ADO.NET默认使用连接池,确保在高并发时重复利用数据库连接,减少连接创建和销毁的开销。不过,要注意正确配置连接字符串,如:
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;Pooling=true;Max Pool Size=100;" providerName="System.Data.SqlClient" />
</connectionStrings>
- 异步操作:使用异步数据库操作方法,避免阻塞线程。例如,在Entity Framework Core中:
public async Task<List<Product>> GetProductsAsync()
{
using (var context = new ApplicationDbContext())
{
return await context.Products.ToListAsync();
}
}
- 优化查询:确保数据库表有适当的索引,使用存储过程代替动态SQL以提高查询性能,并减少不必要的数据返回。
代码优化
- 异步编程:在Web应用中广泛使用
async
和await
关键字,将阻塞操作(如I/O操作)变为异步,释放线程资源,提高应用的吞吐量。例如:
public async Task<string> FetchDataAsync()
{
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetStringAsync("http://example.com/api/data");
return response;
}
}
- 减少内存分配:避免在循环中频繁创建对象,尽量复用对象。例如,使用对象池模式管理一些频繁使用的对象。
- 优化算法和数据结构:选择合适的算法和数据结构,如使用
HashSet
代替List
进行快速查找,使用SortedDictionary
代替Dictionary
进行有序存储等。 - Minification和Compression:对CSS、JavaScript文件进行压缩(Minification),并启用HTTP压缩,减少传输数据量,提高响应速度。在Web.config中配置:
<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<httpCompression>
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="application/*" enabled="true" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/css" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
</system.webServer>
- 依赖注入和控制反转:使用依赖注入框架(如Autofac、Microsoft.Extensions.DependencyInjection)来管理对象的生命周期和依赖关系,提高代码的可测试性和可维护性,同时避免不必要的对象创建。例如,在ASP.NET Core中:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMyService, MyService>();
}
- 性能分析和调优:使用工具如DotMemory、MiniProfiler等对应用进行性能分析,找出性能瓶颈并针对性优化。例如,MiniProfiler可以集成到ASP.NET应用中,直观显示每个请求的执行时间和数据库查询情况。