Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

winforms - C# : Blocking a function call until condition met

I am developing a C# Winforms application, part of the application will be uploading files to a webserver using AsyncUpload (using it,due to the need to use a porgress callback) , In the C# program

i got a simple for loop that calls The Uploading function

 for(int i=0;i < 10 ; i++)
{
  Uploadfun();
}

And the fun does some magic:

Uploadfun()
  { 
  // Logic comes here

   // webClient.UploadFileAsync runs a 2nd thread to perform upload .. 
   webClient.UploadFileAsync(uri, "PUT", fileNameOnHD);  

 }

And a callback that gets called when the Async upload is done

Upload_Completed_callback()
{
  //Callback event
}

Edit

The logic sequence:

  1. Fun gets called (from loop)
  2. Fun logic is executed and done..
  3. Goes back to for loop
  4. Callback will be called eventually, when UploadFileAsync (which is running some logic in another thread) will end

The problem is on the 3rd point, when the execution moves back to the for loop, i need to block the loop from continuing until the callback get called.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So if I understand correctly, you want to call UploadFileAsync then block until the async call has hit your callback. If so, I'd use AutoResetEvent i.e

private readonly AutoResetEvent _signal = new AutoResetEvent(false); 

fun()
  { 
  // Logic comes here

   // runs a 2nd thread to perform upload .. calling "callback()" when done
   webClient.UploadFileAsync(uri, "PUT", fileNameOnHD);  

   _signal.WaitOne();   // wait for the async call to complete and hit the callback     
 }



callback()
 {
   //Callback event
   _signal.Set(); // signal that the async upload completed
 }

Using AutoResetEvent means that the state gets automatically reset after Set has been called and a waiting thread receives the signal via WaitOne


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...