我在不同的用户操作上调用了多种方法客户端上下文。
在每个方法执行上创建它都会导致性能问题。
所以我将其添加为静态变量以实现可重用性,性能平均提高了 5 秒,但随后在某些方法中它开始给出随机问题“版本冲突” on 执行查询()。
但如果我删除静态和空检查,那么它每次都会刷新,性能就会成为问题
有没有一种方法可以创建一次对象,或者至少不是在每次调用时都创建一次对象?
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;
}
}
P.S:我还没有测试过这段代码,但如果这对你有用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)