首页 > 解决方案 > 创建具有类似单例模​​式的可重用性的 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;
        }

    }

标签: c#sharepointcsomsharepoint-clientobjectclientcontext

解决方案


您可以尝试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:我没有测试过这段代码,但如果这对你有用


推荐阅读