1

我的任务是创建与下面的代码具有类似功能的 Java 代码。目前,我正在努力理解代码的作用以及如何在 Java 中模拟效果。

    #region "Send Aggregate Event"

    /// <summary>
    /// Delegate for async sending the AggregateEvent
    /// </summary>
    /// <param name="request"></param>
    public delegate void SendAggregateEventAsync(AE request);
    SendAggregateEventAsync _sendAggregateEventAsync;

    /// <summary>
    /// IAsyncResult pattern to async send the AggregateEvent
    /// </summary>
    /// <param name="request"></param>
    /// <param name="callback"></param>
    /// <param name="state"></param>
    /// <returns></returns>
    public IAsyncResult BeginSendAggregateEvent(AE request, AsyncCallback callback, Object state)
    {
        _sendAggregateEventAsync = new SendAggregateEventAsync(SendAggregateEvent);
        return _sendAggregateEventAsync.BeginInvoke(request, callback, state);

    }

    public void EndSendAggregateEvent(IAsyncResult result)
    {
        object state = result.AsyncState;
        _sendAggregateEventAsync.EndInvoke(result);
    }

    /// <summary>
    /// Send an aggregate event to the Device Webserver
    /// </summary>
    /// <param name="request">The AggregateEvent request</param>
    public void SendAggregateEvent(AE request)
    {
        if (request == null) throw new ArgumentNullException("request");

        String message = ChangeDatesToUTC(MessageHelper.SerializeObject( typeof(AE), request), new String[] { "EventTime" }, url);
        SendMessage(message);
    }
    #endregion 

还有其他几个事件都具有与上面提供的代码相似的代码。从评论中,我了解到该代码旨在异步处理 SendAggregateEvent 方法。我不明白为什么要使用委托修饰符,或者如何在 Java 中复制这种类型的异步处理。

也从阅读这个线程

Java 代表?

我知道在 java 中没有“简单”的方法来模拟委托功能。是否需要委托功能才能异步处理 SendAggregateEvent 方法?如果没有,有人可以建议我怎么做吗?

4

2 回答 2

4

这实际上是 C# 中编写异步代码的旧方式,通常称为Async Programming Model

我对java不够熟悉,但是你真正需要复制这段代码的只是创建一个同步执行操作的方法SendAggregateEvent和一种异步调用它的方法SendAggregateEventAsync

更具体地说是您的一些问题。委托仅用于封装SendAggregateEvent方法,以便可以在可能不同的线程上调用它及其参数(请记住,异步不一定是多线程的)

它是这样的:

var referenceToTaskBeingRun = BeginSomeMethod() 
//the above wraps the actual method and calls it, returning a reference to the task
var results = EndSomeMethod(referenceToTaskBeingRun ); 
//the above sends the reference so that it can be used to get the results from the task. 
//NOTE that this is blocking because you are now waiting for the results, whether they finished or not

现在首选的方法是使用Task Parallel Library,它具有更易于阅读的代码库。

因此,综上所述,关注此代码的关键是您只需要一个方法和该方法的异步版本。实现应该取决于您和您的编程堆栈。不要试图强迫另一个堆栈的实现不属于它……尤其是不再是首选方法的实现。

于 2013-06-03T18:38:34.137 回答
1

根据How to asynchronously call a method in Java的回答,FutureTask是 Java 中异步运行方法的好方法。这是一些异步运行任务的 Java 代码(请参阅它在http://ideone.com/ZtjA5C上运行)

import java.util.*;
import java.lang.*;
import java.util.concurrent.FutureTask;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Before");
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        FutureTask<Object> futureTask = new FutureTask<Object>(new Runnable() {
            public void run()
            {
                System.out.println("Hello async world!");
            }
        }, null);
        System.out.println("Defined");
        executorService.execute(futureTask);
        System.out.println("Running");
        while (!futureTask.isDone())
        {
            System.out.println("Task not yet completed.");

            try
            {
                    Thread.sleep(1);
            }
            catch (InterruptedException interruptedException)
            {
            }
        }
        System.out.println("Done");
    }
}
于 2013-06-03T18:53:44.920 回答