C#:阻塞函数调用,直到满足条件 [英] C# : Blocking a function call until condition met

查看:942
本文介绍了C#:阻塞函数调用,直到满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个C#WinForms应用程序,该应用程序的一部分,将文件上传到使用AsyncUpload一个网络服务器(使用它,由于需要使用porgress回调),在C#程序

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

我有一个简单的for循环调用上传功能

i got a simple for loop that calls The Uploading function

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

和乐趣做一些神奇的:

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
}

修改

的逻辑顺序


  1. 趣味被调用(自环)

  2. 有趣的逻辑被执行,完成..

  3. 返回上循环

  4. 回调最终会被调用,当UploadFileAsync(这是运行在另一个线程一些逻辑)将结束

  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

问题是第3点,当执行移回用于循环,我需要阻止继续循环,直到回调得到调用

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.

推荐答案

所以,如果我理解正确的话,你要调用 UploadFileAsync 然后阻塞,直到异步调用击中你的回调。如果是这样,我会使用的AutoResetEvent

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
 }

使用的AutoResetEvent 意味着国家被后设置自动复位已经调用了一个等待线程通过的WaitOne

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

这篇关于C#:阻塞函数调用,直到满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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