Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How to wait in a function until a boolean variable set to true.

for example

C#
volatile bool fileSendingCompleted=false;
bool fileSentStatus=false;
bool sendfile()
{
//am calling a thread,from that thread timer will be called,so am going based on boolean variable.
while(fileSendingCompleted==false) ;//fileSendingCompletedwill be updated in thread
return fileSentStatus;//fileSentStatus will be updated in thread
}

If am doing like this, application getting hang,Please tell me how to wait in this function.
Posted
Updated 9-Jan-14 2:33am
v4

1 solution

The answer is don't use a bool to synchronize threads, use an EventWaitHandle, for example a AutoResetEvent.

This shows how one thread can be made to wait for another:

C#
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadApplication {
    class Program {

        static void Main(string[] args) {

            var are = new AutoResetEvent(false);

            var producer = Task.Factory.StartNew(() => {
                Console.WriteLine("I am producer!");
                Thread.Sleep(1000);
                Console.WriteLine("Producer is done!");
                are.Set();
            });

            var consumer = Task.Factory.StartNew(() => {
                Console.WriteLine("I am consumer, I will wait for producer!");
                are.WaitOne();
                Console.WriteLine("Producer is done, so now consumer is done!");
            });

            Task.WaitAll(producer, consumer);
        }
    }
}
Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900