c# - 创建具有类似单例模式的可重用性的 CSOM ClientContext
问题描述
我在使用ClientContext的不同用户操作上调用了多个方法。在每次方法执行时创建它都会导致性能问题。
因此,我将其添加为静态变量以实现可重用性,性能平均提高了 5 秒,但随后在某些方法中,它开始在ExecuteQuery()上随机发出“版本冲突”问题。但是如果我删除静态和空检查,那么它每次都会刷新,性能就会成为问题
有什么方法可以创建这个对象的一个时间对象,或者至少不是在每次调用时创建一个对象?ClientContext 的默认到期时间是多少?
创建ClientContext对象的代码:
public class SPConnection
{
public static ClientContext SharepointClientContext { get; set; }
public static ClientContext GetSharePointContext()
{
try
{
if (SharepointClientContext == null)
{
string appId = System.Configuration.ConfigurationManager.AppSettings["appId"];
string appSecret = System.Configuration.ConfigurationManager.AppSettings["appSecret"];
string siteUrl = System.Configuration.ConfigurationManager.AppSettings["siteUrl"];
var authManager = new OfficeDevPnP.Core.AuthenticationManager();
using (ClientContext clientContext = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
{
SharepointClientContext = clientContext;
return clientContext;
}
}
else
return SharepointClientContext;
}
catch (Exception ex)
{
iChange.Web.API.Authentication.SPConnection.InsertRecordToTableErrorLog("Mucebat:"+ex.Message, ex.StackTrace.ToString());
throw ex;
}
}
使用它的方法之一的代码:
public bool UpdateProfilePic(updateprofilepicmodel model)
{
using (ClientContext context = SPConnection.GetSharePointContext())
{
List list = context.Web.Lists.GetByTitle("Members");
ListItemCreationInformation info = new ListItemCreationInformation();
ListItem item = list.GetItemById(model.MemberId);
item["ProfilePicture"] = model.ProfilepicUrl;
item.Update();
context.ExecuteQuery();
return true;
}
}
解决方案
您可以尝试ExecuteQueryAsync
与异步任务结合使用以提高性能吗?例如
public async Task <bool> UpdateProfilePic(updateprofilepicmodel model)
{
using (ClientContext context = SPConnection.GetSharePointContext())
{
List list = context.Web.Lists.GetByTitle("Members");
ListItem item = list.GetItemById(model.MemberId);
context.Load(item);
Task t1 = context.ExecuteQueryAsync();
await t1.ContinueWith((t) =>
{
item["ProfilePicture"] = model.ProfilepicUrl;
item.Update();
Task t2 = context.ExecuteQueryAsync();
});
await t2.ContinueWith((t) =>
{
// do some stuff here if needed
});
return true;
}
}
PS:我没有测试过这段代码,但如果这对你有用
推荐阅读
- forth - GForth:将浮点数转换为字符串
- java - 如何在不丢失元数据的情况下从 InputStream 保存视频文件?
- javascript - 根据 innerWidth 属性更改元素宽度
- android - RxJava 计算线程 + Android Keystore 阻塞 UI?
- pyspark - pyspark.sql.functions abs() 因 PySpark 列输入而失败
- python - 重构python代码:列表的动态解包
- regex - 批处理:FINDSTR 正则表达式不起作用
- eclipse - 如何让水平两指触摸板滚动在 Eclipse 中工作?
- google-chrome-extension - 如何使用 Puppeteer 调用 Chrome 扩展程序?
- python - SQLAlchemy,你能在一个查询中得到一个特定实体的列值吗(使用 column.name)?