Threading and asynchronous operations in C#

后端 未结 1 1558
甜味超标
甜味超标 2020-12-21 11:42

I\'m an old dog trying to learn a new trick. I\'m extremely familiar with a language called PowerBuilder and in that language, when you want to do things asynchronously, you

相关标签:
1条回答
  • 2020-12-21 12:24

    BlockingCollection makes putting this kind of thing together pretty easy:

    // the queue
    private BlockingCollection<Message> MessagesQueue = new BlockingCollection<Message>();
    
    
    // the consumer
    private MessageParser()
    {
        foreach (var msg in MessagesQueue.GetConsumingEnumerable())
        {
            var parsedMessage = ParseMessage(msg);
            // do something with the parsed message
        }
    }
    
    // In your main program
    // start the consumer
    var consumer = Task.Factory.StartNew(() => MessageParser(),
        TaskCreationOptions.LongRunning);
    
    // the main loop
    while (messageAvailable)
    {
        var msg = GetMessageFromTcp();
        // add it to the queue
        MessagesQueue.Add(msg);
    }
    
    // done receiving messages
    // tell the consumer that no more messages will be added
    MessagesQueue.CompleteAdding();
    
    // wait for consumer to finish
    consumer.Wait();
    

    The consumer does a non-busy wait on the queue, so it's not eating CPU resources when there's nothing available.

    0 讨论(0)
提交回复
热议问题