代码之家  ›  专栏  ›  技术社区  ›  Chris Nicol

新的“等待”功能是做什么的?[关闭]

  •  82
  • Chris Nicol  · 技术社区  · 16 年前

    await 功能是什么?

    5 回复  |  直到 12 年前
        1
  •  62
  •   GameScripting    14 年前

    他们只是 talked about this at PDC

    Await与.NET中的任务(并行编程)一起使用。这是.NET下一个版本中引入的关键字。它或多或少允许您“暂停”方法的执行以等待任务完成执行。下面是一个简单的例子:

    //create and run a new task  
    Task<DataTable> dataTask = new Task<DataTable>(SomeCrazyDatabaseOperation);
    
    //run some other code immediately after this task is started and running  
    ShowLoaderControl();  
    StartStoryboard();
    
    //this will actually "pause" the code execution until the task completes.  It doesn't lock the thread, but rather waits for the result, similar to an async callback  
    // please so also note, that the task needs to be started before it can be awaited. Otherwise it will never return
    dataTask.Start();
    DataTable table = await dataTask;
    
    //Now we can perform operations on the Task result, as if we're executing code after the async operation completed  
    listBoxControl.DataContext = table;  
    StopStoryboard();  
    HideLoaderControl();
    
        2
  •  47
  •   KeithS    15 年前

    基本上 async 和 await 等待 ,它标记异步方法调用,然后在异步操作完成后继续。这允许您在应用程序的主线程中调用方法,并异步处理复杂的工作,而无需显式定义线程和连接,也无需阻塞应用程序的主线程。

    认为它有点类似于 yield return 产生IEnumerable的方法中的语句。当运行时到达 yield 生利

    类似地,标记为 必须至少有一个 等待 等待 ,运行时将保存当前线程的状态和调用堆栈,进行异步调用,并返回到运行时的消息循环以处理下一条消息并保持应用程序响应。当异步操作完成时,在下一个调度机会中,向上推送异步操作的调用堆栈并继续,就好像调用是同步的一样。

    生利 简化了自定义枚举的生成。有了几个关键字和一些背景知识,您就可以跳过传统异步模式中所有令人困惑且经常出错的细节。这在任何事件驱动的GUI应用程序(如Winforms、Silverlight的WPF)中都是非常宝贵的。

        3
  •  31
  •   Anri dprahut    13 年前

    目前接受的答案是误导性的。 await 首先,它只能用于标记为的方法或lambdas async 然后回来 Task 或 void 任务 在此方法中运行的实例。

    下面是一个例子:

    internal class Program
    {
        private static void Main(string[] args)
        {
            var task = DoWork();
            Console.WriteLine("Task status: " + task.Status);
            Console.WriteLine("Waiting for ENTER");
            Console.ReadLine();
        }
    
        private static async Task DoWork()
        {
            Console.WriteLine("Entered DoWork(). Sleeping 3");
            // imitating time consuming code
            // in a real-world app this should be inside task, 
            // so method returns fast
            Thread.Sleep(3000);
    
            await Task.Run(() =>
                {
                    for (int i = 0; i < 10; i++)
                    {
                        Console.WriteLine("async task iteration " + i);
                        // imitating time consuming code
                        Thread.Sleep(1000);
                    }
                });
    
            Console.WriteLine("Exiting DoWork()");
        }
    }
    

    输出:


    异步任务迭代0
    任务状态:等待激活


    异步任务迭代2

    异步任务迭代4
    异步任务迭代5
    异步任务迭代6

    异步任务迭代8
    异步任务迭代9
    退出DOWORK()

        4
  •  11
  •   Todd Menier    10 年前

    $.post(url, values, function(data) {
      // AJAX call completed, do something with returned data here
    });
    

    我们在回调函数中处理结果的原因是,在等待AJAX调用返回时不会阻塞当前线程。只有当响应准备就绪时,回调才会被触发,同时释放当前线程执行其他操作。

    现在,如果JavaScript支持 await 关键字(当然不是( yet!

    var data = await $.post(url, values);
    // AJAX call completed, do something with returned data here
    

    这要干净得多,但看起来我们确实引入了同步的阻塞代码。但是(假)JavaScript编译器会在 等待 并将其连接到回调中,因此在运行时,第二个示例的行为将与第一个示例一样。

    许多 为你举重。更多的话,我推荐 FAQs 然后 Stephen Cleary's blog series

        5
  •  -2
  •   Ilya Gazman    12 年前

    /**
     * @author Ilya Gazman
     */
    public abstract class SynchronizedTask{
    
        private ArrayList<Runnable> listeners = new ArrayList<Runnable>();
    
        private static final ThreadPoolExecutor threadPoolExecutor =  new ThreadPoolExecutor(6, 6, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1000));
    
        public final void await(Runnable listener){
            synchronized (this) {
                listeners.add(listener);
            }
        }
    
        public void excecute(){
            onExcecute();
            for (int i = listeners.size() - 1; i >= 0; i--) {
                Runnable runnable;
                synchronized (this) {
                    runnable = listeners.remove(i);
                }
                threadPoolExecutor.execute(runnable);
            }
        }
    
        protected abstract void onExcecute();
    }
    

    您的应用程序将按如下方式使用它:

    public class Test{
        private Job job = new Job();
    
        public Test() {
            craeteSomeJobToRunInBackground();
            methode1();
            methode2();
        }
    
        private void methode1(){
            System.out.println("Running methode 1");
            job.await(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println("Continue to running methode 1");
                }
            });
        }
    
        private void methode2(){
            System.out.println("Running methode 2");
        }
    
        private void craeteSomeJobToRunInBackground() {
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    job.excecute();
                }
            }).start();
        }
    
        private class Job extends SynchronizedTask{
    
            @Override
            protected void onExcecute() {
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Job is done");
            }
        }
    }