Пример #1
0
        /// <summary>Begins to serialize the objects to the specified file using the specified encoding.</summary>
        /// <param name="objects">The collection of objects that must be serialized.</param>
        /// <param name="filePath">The name of the output file.</param>
        /// <param name="encoding">The encoding that must be used to serialize the data.</param>
        /// <param name="callback">The method to be called when the asynchronous operation is completed.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous request from other requests.</param>
        /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
        public IAsyncResult BeginSerialize(IEnumerable <T> objects, string filePath, Encoding encoding, AsyncCallback callback, object state)
        {
            AsyncResult <int>          result    = new AsyncResult <int>(callback, state);
            SerializePropertyContainer container =
                new SerializeToFilePropertyContainer {
                Objects = objects, FilePath = filePath, Encoding = encoding, AsyncResult = result
            };

            ThreadPool.QueueUserWorkItem(this.SerializeToFileHelper, container);
            return(result);
        }
Пример #2
0
        /// <summary>Executes the <see cref="Serialize(IEnumerable{T},string,Encoding)"/> method in a separate thread. This is used to support
        /// asynchronous operations.</summary>
        /// <param name="propertyContainer">The object that holds properties that are required for the asynchronous operation.</param>
        private void SerializeToFileHelper(object propertyContainer)
        {
            Guard.ArgumentIsOfType <SerializeToFilePropertyContainer>(propertyContainer, nameof(propertyContainer), "The specified object was not of the expected type SerializeToFilePropertyContainer");
            SerializeToFilePropertyContainer container = propertyContainer as SerializeToFilePropertyContainer;

            try {
                int result = this.Serialize(container.Objects, container.FilePath, container.Encoding);
                container.AsyncResult.SetAsCompleted(result, null, false);
            }
            catch (Exception ex) {
                /* We deliberately catch every exception. It is up to the caller of EndSerialize() to do a more fine-grained exception handling */
                container.AsyncResult.SetAsCompleted(-1, ex, false);
            }
        }