本文介绍了如何在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.
推荐答案
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#中的函数中等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!