[英]Create CSOM ClientContext with re-usability like singleton pattern
我對使用ClientContext的不同用戶操作調用了多種方法。 在每次方法執行時創建它都會導致性能問題。
所以我將它添加為 static 變量以實現可重用性,性能平均提高了 5 秒,但隨后在某些方法中它開始在ExecuteQuery()上隨機出現“版本沖突”問題。 但是如果我刪除 static 和 null 檢查,那么它每次都會刷新並且性能成為問題
有沒有辦法創建一次 object 或至少不是每次調用? ClientContext 的默認到期時間是多少?
創建ClientContext object的代碼:
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:我沒有測試過這段代碼,但如果這對你有用
您可以嘗試在更新之前加載列表項。 修改代碼如下,檢查是否有效。
public 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);
context.ExecuteQuery();
item["ProfilePicture"] = model.ProfilepicUrl;
item.Update();
context.ExecuteQuery();
return true;
}
}
如果上述代碼不起作用,您可以在列表設置中啟用“成員”列表的版本以檢查問題是否仍然存在。
您不能將 ClientContext 用作 static object。在代碼中,您正在使用段中編寫代碼。 ClientContext object 將在using塊執行完成后銷毀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.