如何在c#中的函数中等待 [英] How to wait in a function in c#

查看:1049
本文介绍了如何在c#中的函数中等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在函数中等待,直到布尔变量设置为true。



例如



How to wait in a function until a boolean variable set to true.

for example

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.

推荐答案

答案是不要使用 bool 来同步线程,使用 EventWaitHandle ,例如 AutoResetEvent



这显示如何一个线程c等待另一个:



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:

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);
        }
    }
}

希望这会有所帮助,

Fredrik

Hope this helps,
Fredrik


这篇关于如何在c#中的函数中等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆