示例#1
0
        public async Task AsyncTest()
        {
            /* Arrange */
            var worker = BackgroundWorker.Create();

            /* Act */
            await worker.RunWorkerAsync(DoWorkAsync);

            /* Assert */
            Assert.AreEqual(10, i);
        }
示例#2
0
        public void CancelTest()
        {
            var tokenSource = new CancellationTokenSource();
            /* Arrange */
            var worker = BackgroundWorker.Create();

            /* Act */
            var task = worker.RunWorkerAsync(DoWorkAsync, tokenSource.Token);

            tokenSource.Cancel();

            /* Assert */
            // ReSharper disable once MethodSupportsCancellation
            Assert.That(() => task.Wait(), Throws.TypeOf <AggregateException>().And.InnerException.AssignableFrom <TaskCanceledException>());
        }
示例#3
0
        internal static async Task RunSplitScript(Stream stream, string ConnectionString, int TimeOut = 0, string SplitOn = DEFAULT_SPLIT, Encoding encoding = null, bool detectEncodingFromByteOrderMarks = true, int bufferSize = 4096)
        {
            DateTime start = DateTime.Now;

            Exception toThrow = null;

            bool readPos = true;

            encoding = encoding ?? Encoding.Default;

            ConcurrentQueue <AsyncSqlCommand> Commands = new ConcurrentQueue <AsyncSqlCommand>();
            bool ReadComplete = false;

            BackgroundWorker SQLWorker = BackgroundWorker.Create((worker) =>
            {
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    Server server = new Server(new ServerConnection(connection));
                    server.ConnectionContext.StatementTimeout = TimeOut;
                    connection.Open();

                    while (!ReadComplete || Commands.Any())
                    {
                        if (Commands.Any())
                        {
                            if (Commands.TryDequeue(out AsyncSqlCommand cmd))
                            {
                                try
                                {
                                    StaticLogger.Log($"Executing Command {cmd.CommandNumber} - {Math.Round(cmd.Progress, 2)}%");

                                    server.ConnectionContext.ExecuteNonQuery(cmd.Text);
                                }
                                catch (Exception ex)
                                {
                                    List <string> AcceptableErrors = new List <string>()
                                    {
                                        "is not a valid login or you do not have permission",
                                        "User does not have permission to perform this action",
                                        "not found. Check the name again.",
                                        " already exists in the current database."
                                    };

                                    if (!AcceptableErrors.Any(ae => ex.Message.Contains(ae)) && (ex.InnerException == null || !AcceptableErrors.Any(ae => ex.InnerException.Message.Contains(ae))))
                                    {
                                        StaticLogger.Log(cmd.Text + Environment.NewLine + ex.Message);
                                        toThrow = ex;
                                        throw;
                                    }
                                }
                            }
                        }
                        else
                        {
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                }
            });

            BackgroundWorker FileReadWorker = BackgroundWorker.Create((worker) =>
            {
                using (StreamReader reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false))
                {
                    long streamLength = 0;

                    try
                    {
                        streamLength = reader.BaseStream.Length;
                    }
                    catch (Exception)
                    {
                        readPos = false;
                    }
                    // Open the connection and execute the reader.

                    int BufferLength = SplitOn.Length;

                    char[] buffer     = new char[BufferLength];
                    char[] splitArray = SplitOn.ToCharArray();

                    int bufferPointer = 0;

                    StringBuilder currentCommand = new StringBuilder(5000);

                    int commandNumber = 0;
                    bool wrapped      = false;

                    while (!reader.EndOfStream)
                    {
                        char currentChar = (char)reader.Read();

                        buffer[bufferPointer] = currentChar;

                        bool breakScript = true;

                        for (int i = 0; i < BufferLength; i++)
                        {
                            if (buffer[(bufferPointer - ((buffer.Length - 1) - i) % buffer.Length + buffer.Length) % buffer.Length] != SplitOn[i])
                            {
                                breakScript = false;
                                break;
                            }
                        }

                        bufferPointer++;

                        if (bufferPointer == buffer.Length)
                        {
                            wrapped       = true;
                            bufferPointer = 0;
                        }

                        if (breakScript)
                        {
                            long pos      = long.MaxValue;
                            long progress = 0;
                            if (readPos)
                            {
                                pos      = reader.BaseStream.Position;
                                progress = pos / streamLength * 100;
                            }
                            AsyncSqlCommand icmd = new AsyncSqlCommand(currentCommand.ToString(), progress, ++commandNumber);

                            while (Commands.Count > 5)
                            {
                                if (SQLWorker.IsBusy)
                                {
                                    System.Threading.Thread.Sleep(100);
                                }
                                else
                                {
                                    if (toThrow != null)
                                    {
                                        throw toThrow;
                                    }
                                    else
                                    {
                                        throw new Exception("Sql worker ended unexpectedly");
                                    }
                                }
                            }

                            Commands.Enqueue(icmd);

                            currentCommand.Clear();

                            buffer        = new char[BufferLength];
                            bufferPointer = 0;
                            wrapped       = false;
                        }
                        else
                        {
                            if (wrapped)
                            {
                                currentCommand.Append(buffer[bufferPointer]);
                            }
                        }
                    }

                    int finalPointer = bufferPointer;
                    bool breakBuffer;
                    //Grab any straying characters from the buffer;

                    do
                    {
                        bufferPointer++;

                        if (bufferPointer == buffer.Length)
                        {
                            wrapped       = true;
                            bufferPointer = 0;
                        }

                        breakBuffer = bufferPointer == finalPointer;

                        if (breakBuffer)
                        {
                            break;
                        }

                        currentCommand.Append(buffer[bufferPointer]);
                    } while (true);

                    AsyncSqlCommand lcmd = new AsyncSqlCommand(currentCommand.ToString(), ((reader.BaseStream.Position / streamLength) * 100), commandNumber);

                    Commands.Enqueue(lcmd);

                    ReadComplete = true;
                }
            });

            Task <bool> FileReadResult   = FileReadWorker.RunWorkerAsync();
            Task <bool> SqlProcessResult = SQLWorker.RunWorkerAsync();

            await FileReadResult;
            await SqlProcessResult;
        }