简体   繁体   English

C#委托Java和方法的异步处理

[英]C# delegates to Java and asynchronous handling of methods

I have been tasked with creating Java code with similar functionality to the code below. 我的任务是创建具有与以下代码类似功能的Java代码。 Currently I am struggling with understanding exactly what the code does and how to simulate the effect in 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 

There are several other events all with similar code to the provided above. 还有其他几个事件,所有事件的代码都与上面提供的类似。 From the comments, I understand that the code is intended to asynchronously handle the SendAggregateEvent method. 从这些注释中,我了解到该代码旨在异步处理SendAggregateEvent方法。 What I do not understand is why the delegate modifier is used, or how to replicate this type of asynchronous handling in Java. 我不明白的是为什么使用委托修饰符,或者如何在Java中复制这种类型的异步处理。

Also from reading this thread 另外从阅读此线程

Java Delegates? Java代表?

I understand that there is no "easy" way to simulate the delegate functionality in java. 我了解没有模拟Java中委托功能的“简便”方法。 Is it necessary to have the delegate functionality to have the SendAggregateEvent method handled asynchronously? 是否需要具有委托功能才能异步处理SendAggregateEvent方法? If not, can someone suggest how I would do this? 如果没有,有人可以建议我怎么做吗?

This is actually the old way of writing async code in C#, commonly referred to as the Async Programming Model 这实际上是用C#编写异步代码的旧方法,通常称为“ 异步编程模型”

I am not familiar enough with java, but all you really need to replicate this code is to create a method that does the action synchronously SendAggregateEvent and a means to call that asynchronously SendAggregateEventAsync 我对Java不够熟悉,但是复制此代码所需SendAggregateEvent只是创建一个同步执行SendAggregateEvent动作的方法和异步调用SendAggregateEventAsync

More specifically to some of your questions. 更具体地说,是针对您的某些问题。 The delegate is only being used to encapsulate the SendAggregateEvent method so that it and its parameters can be invoked on a potentially different thread (keeping in mind that async is not necessarily multi-threaded) 委托仅用于封装SendAggregateEvent方法,以便可以在可能不同的线程上调用它及其参数(请注意,异步不一定是多线程的)

It goes something like this: 它是这样的:

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

The preferred way to do this now is to use the Task Parallel Library , which has a much easier to read code base. 现在,执行此操作的首选方法是使用Task Parallel Library ,它具有更易于阅读的代码库。

So, all of that being said, the key to focus on this code would be that you just need a method and an async version of that method. 因此,综上所述,专注于此代码的关键是您只需要一个方法和该方法的异步版本。 The implementation should be up to you and your programming stack. 实现应由您和您的编程堆栈来决定。 Do not try to force another stack's implementation where it does not belong...especially an implementation that is not even the preferred methodology any longer. 不要试图强迫另一个不属于它的堆栈实现,尤其是不再是首选方法的实现。

According to How to asynchronously call a method in Java 's answer, FutureTask is a good way in Java to asynchronously run a method. 根据如何在Java的答案中异步调用方法FutureTask是Java中异步运行方法的好方法。 Here's some Java code that runs a task asynchronously (see it run at http://ideone.com/ZtjA5C ) 这是一些异步运行任务的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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM