Ориентированная на многопотоковое исполнение реализация очереди блокирования на.NET

"jsonp" Вы можете попробовать.

   <script type="text/javascript">
 jQuery(document).ready(function(){ 
    $.ajax({
         type: "get",
         async: false,
         url: "http://example/abc/service.php ",
         dataType: "jsonp",
         jsonp: "callback",
         jsonpCallback:"flightHandler",
         success: function(json){
             alert(json.price);
         },
         error: function(){
             alert('fail');
         }
     });
 });
 </script>
17
задан Shrike 29 April 2009 в 09:05
поделиться

7 ответов

How about this one Creating a blocking Queue in .NET?

If you need it for .NET 1.1 (I wasn't sure from the question), just drop the generics and replace T with object.

9
ответ дан 30 November 2019 в 12:20
поделиться

Queue.Synchronized http://msdn.microsoft.com/en-us/library/system.collections.queue.synchronized(VS.71).aspx

Is a starting point anyways, I've never used a Blocking Queue. Sorry for the not so relevant post.

1
ответ дан 30 November 2019 в 12:20
поделиться

Microsoft has a pretty nice sample about this:

//Copyright (C) Microsoft Corporation.  All rights reserved.

using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;

// The thread synchronization events are encapsulated in this 
// class to allow them to easily be passed to the Consumer and 
// Producer classes. 
public class SyncEvents
{
    public SyncEvents()
    {
        // AutoResetEvent is used for the "new item" event because
        // we want this event to reset automatically each time the
        // consumer thread responds to this event.
        _newItemEvent = new AutoResetEvent(false);

        // ManualResetEvent is used for the "exit" event because
        // we want multiple threads to respond when this event is
        // signaled. If we used AutoResetEvent instead, the event
        // object would revert to a non-signaled state with after 
        // a single thread responded, and the other thread would 
        // fail to terminate.
        _exitThreadEvent = new ManualResetEvent(false);

        // The two events are placed in a WaitHandle array as well so
        // that the consumer thread can block on both events using
        // the WaitAny method.
        _eventArray = new WaitHandle[2];
        _eventArray[0] = _newItemEvent;
        _eventArray[1] = _exitThreadEvent;
    }

    // Public properties allow safe access to the events.
    public EventWaitHandle ExitThreadEvent
    {
        get { return _exitThreadEvent; }
    }
    public EventWaitHandle NewItemEvent
    {
        get { return _newItemEvent; }
    }
    public WaitHandle[] EventArray
    {
        get { return _eventArray; }
    }

    private EventWaitHandle _newItemEvent;
    private EventWaitHandle _exitThreadEvent;
    private WaitHandle[] _eventArray;
}

// The Producer class asynchronously (using a worker thread)
// adds items to the queue until there are 20 items.
public class Producer 
{
    public Producer(Queue<int> q, SyncEvents e)
    {
        _queue = q;
        _syncEvents = e;
    }
    public void ThreadRun()
    {
        int count = 0;
        Random r = new Random();
        while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                while (_queue.Count < 20)
                {
                    _queue.Enqueue(r.Next(0, 100));
                    _syncEvents.NewItemEvent.Set();
                    count++;
                }
            }
        }
        Console.WriteLine("Producer thread: produced {0} items", count);
    }
    private Queue<int> _queue;
    private SyncEvents _syncEvents;
}

// The Consumer class uses its own worker thread to consume items
// in the queue. The Producer class notifies the Consumer class
// of new items with the NewItemEvent.
public class Consumer
{
    public Consumer(Queue<int> q, SyncEvents e)
    {
        _queue = q;
        _syncEvents = e;
    }
    public void ThreadRun()
    {
        int count = 0;
        while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                int item = _queue.Dequeue();
            }
            count++;
        }
        Console.WriteLine("Consumer Thread: consumed {0} items", count);
    }
    private Queue<int> _queue;
    private SyncEvents _syncEvents;
}

public class ThreadSyncSample
{
    private static void ShowQueueContents(Queue<int> q)
    {
        // Enumerating a collection is inherently not thread-safe,
        // so it is imperative that the collection be locked throughout
        // the enumeration to prevent the consumer and producer threads
        // from modifying the contents. (This method is called by the
        // primary thread only.)
        lock (((ICollection)q).SyncRoot)
        {
            foreach (int i in q)
            {
                Console.Write("{0} ", i);
            }
        }
        Console.WriteLine();
    }

    static void Main()
    {
        // Configure struct containing event information required
        // for thread synchronization. 
        SyncEvents syncEvents = new SyncEvents();

        // Generic Queue collection is used to store items to be 
        // produced and consumed. In this case 'int' is used.
        Queue<int> queue = new Queue<int>();

        // Create objects, one to produce items, and one to 
        // consume. The queue and the thread synchronization
        // events are passed to both objects.
        Console.WriteLine("Configuring worker threads...");
        Producer producer = new Producer(queue, syncEvents);
        Consumer consumer = new Consumer(queue, syncEvents);

        // Create the thread objects for producer and consumer
        // objects. This step does not create or launch the
        // actual threads.
        Thread producerThread = new Thread(producer.ThreadRun);
        Thread consumerThread = new Thread(consumer.ThreadRun);

        // Create and launch both threads.     
        Console.WriteLine("Launching producer and consumer threads...");        
        producerThread.Start();
        consumerThread.Start();

        // Let producer and consumer threads run for 10 seconds.
        // Use the primary thread (the thread executing this method)
        // to display the queue contents every 2.5 seconds.
        for (int i = 0; i < 4; i++)
        {
            Thread.Sleep(2500);
            ShowQueueContents(queue);
        }

        // Signal both consumer and producer thread to terminate.
        // Both threads will respond because ExitThreadEvent is a 
        // manual-reset event--so it stays 'set' unless explicitly reset.
        Console.WriteLine("Signaling threads to terminate...");
        syncEvents.ExitThreadEvent.Set();

        // Use Join to block primary thread, first until the producer thread
        // terminates, then until the consumer thread terminates.
        Console.WriteLine("main thread waiting for threads to finish...");
        producerThread.Join();
        consumerThread.Join();
    }
}
0
ответ дан 30 November 2019 в 12:20
поделиться

Имейте в виду, что блокировка вызывающего кода может быть лучшим вариантом, если вы полностью контролируете его. Рассмотрите возможность обращения к вашей очереди в цикле: вы будете без нужды устанавливать блокировки несколько раз, что может привести к снижению производительности.

0
ответ дан 30 November 2019 в 12:20
поделиться

1) Зачем вам это делать? Их более 3500 (по состоянию на февраль 2012)?

2) Вы просмотрели Представления задач CRAN и пакет ctv , позволяющий устанавливать пакеты из данной задачи?

3) Вопрос жирным шрифтом - это простой индексный запрос, который можно выполнить вручную (и, кроме того, см. help (набор) )

R> available <- LETTERS                  # a simple set
R> installed <- LETTERS[c(1:10, 15:26)]  # a simple subset
R> available[ ! available %in% installed ]
[1] "K" "L" "M" "N"
R> 

Edit: в ответ на ваш последующий запрос:

a) Если пакет не проходит 'R CMD check' в Linux и Windows, он не загружается в CRAN. Чтобы эта работа была выполнена.

б) Получение всего зависит от вашего конца - это тоже работа, как вы увидите. Мы сделали это для cran2deb, который находится по адресу http://debian.cran.r-project.org (который делает полномасштабное построение пакета Debian, которое больше, чем просто установка). Мы получаем около 2050 из 2150 построенных пакетов. Есть несколько мы отказываемся строить из-за лицензии, несколько мы не можем из-за отсутствия заголовков или libs и несколько мы не можем построить, потому что они нуждаются, например, BioConductor пакеты.

-121--2768705-

Стандарт C уже имеет набор «безопасных» версий этих функций.
(Для конкретного определения термина safe)

snprintf () (и семейство) предоставляют необходимые функции безопасности. Проверка переполнения буфера.
Компилятор gcc дополнительно выполняет проверку последовательности формата (но лучше, чем MS, поскольку проверка выполняется во время компиляции).

fopen()             Not sure how you make that safer?
vfprintf            --  These are low level functions
vsprintf            --  These are low level functions
sprintf             snprintf
strncpy             Already the safe version
strcpy              strncpy
strcat              strncat
-121--2881572-

Для справки в приложении .NET 4 вводится тип System.Collections.Concurrent.Colvation < T > . Для неблокирующей очереди можно использовать System.Collections.Concurrent.ConcurrentQueue < T > . Обратите внимание на то, что ConcurrentQueue < T > , скорее всего, будет использоваться в качестве базового хранилища данных для коллекции ConcurrentQueue < T > для использования OP.

20
ответ дан 30 November 2019 в 12:20
поделиться

Пример Microsoft является хорошим, но он не инкапсулирован в класс. Кроме того, это требует, чтобы потребительскую нить выполнял в MTA (из-за вызова операций). Есть некоторые случаи, в которых вам может потребоваться запустить в STA (E.g., если вы делаете COM Interop). В этих случаях Wainany не может быть использован.

У меня есть простой класс блокировки очереди, который преодолевает эту проблему здесь: http://element533.blogspot.com/2010/01/stoppapable-blocking-queue-for-let.html

1
ответ дан 30 November 2019 в 12:20
поделиться

Да, .NET4 содержит параллельные коллекции. BTW, очень хорошее руководство по параллельным расширениям от команды pfx - http://www.microsoft.com/downloads/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&displaylang=en.

pfx также доступен для .net 3.5 как часть реактивных расширений.

1
ответ дан 30 November 2019 в 12:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: