Пример #1
0
    private BackgroundWorker GetBackgroundWorker <T, K>(Func <T, K> doWork, WorkerCompletedDelegate <K> workerCompleted)
    {
        BackgroundWorker bw = new BackgroundWorker();

        bw.WorkerReportsProgress      = false;
        bw.WorkerSupportsCancellation = false;

        bw.DoWork += (sender, args) =>
        {
            if (doWork != null)
            {
                args.Result = (K)doWork((T)args.Argument);
            }
        };

        bw.RunWorkerCompleted += (sender, args) =>
        {
            if (workerCompleted != null)
            {
                workerCompleted((K)args.Result, args.Error);
            }
            Queue.Dequeue();
            lock (lockingObject1)
            {
                if (Queue.Count > 0)
                {
                    ((QueueItem)this.Queue.Peek()).RunWorkerAsync();
                }
            }
        };
        return(bw);
    }
Пример #2
0
    /// <summary>
    /// doWork is a method with one argument
    /// </summary>
    /// <typeparam name="T">is the type of the input parameter</typeparam>
    /// <typeparam name="K">is the type of the output result</typeparam>
    /// <param name="inputArgument"></param>
    /// <param name="doWork"></param>
    /// <param name="workerCompleted"></param>
    public void RunAsync <T, K>(Func <T, K> doWork, T inputArgument, WorkerCompletedDelegate <K> workerCompleted)
    {
        BackgroundWorker bw = GetBackgroundWorker <T, K>(doWork, workerCompleted);

        Queue.Enqueue(new QueueItem(bw, inputArgument));

        lock (lockingObject1)
        {
            if (Queue.Count == 1)
            {
                ((QueueItem)this.Queue.Peek()).RunWorkerAsync();
            }
        }
    }