tread complete notification

  • Thread starter Thread starter bill
  • Start date Start date
B

bill

How would I signal the main app when a thread has completed a task.

The thread must remain actice. Every time it reads a given number of bytes
it must let the main app know, then wait until more data shows up. The
number of bytes it reads varies.

Thanks,
Bill
 
Bill,

This is a very classic producer - consumer issue. Multi-threading
programming 101.

I give you an example here, I get this from some body else's website.
Here a monitor is used. I believe there are other approaches too..


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

namespace ProduceConsumer
{
class Program
{
static ProducerConsumer _queue;
static void Main(string[] args)
{
_queue = new ProducerConsumer();
new Thread(new ThreadStart(ConsumerJob)).Start();

Random rng = new Random(0);
for (int i = 0; i < 10; i++)
{
Console.WriteLine ("Producing {0}", i);
_queue.Produce(i);
Thread.Sleep(1000);
}
}

static void ConsumerJob()
{
Random rng = new Random(1);
for (int i = 0; i < 10; i++)
{
int iConsume = _queue.Consume();
Console.WriteLine("\t\t\tConsuming {0}", iConsume);
Thread.Sleep(rng.Next(1000));
}
}
}

public class ProducerConsumer
{
readonly object listLock = new object();
Queue<int> queue = new Queue<int>();

public void Produce(int i)
{
lock (listLock)
{
queue.Enqueue(i);
if (queue.Count == 1)
{
Monitor.Pulse(listLock);
}
}
}

public int Consume()
{
lock (listLock)
{
while (queue.Count == 0)
{
Monitor.Wait(listLock);
}
return queue.Dequeue();
}
}
}
}
 
Hi,

You can use Control.Invoke to force the execution of a method in the UI
thread, this can be used for a progressBar , etc


cheers,
 
Back
Top