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
235 views
in Technique[技术] by (71.8m points)

c# - How to use Visual Studio - generated async WCF calls?

My OperationContract:

public List<MessageDTO> GetMessages()
        {
            List<MessageDTO> messages = new List<MessageDTO>();
            foreach (Message m in _context.Messages.ToList())
            {
                messages.Add(new MessageDTO()
                {
                    MessageID = m.MessageID,
                    Content = m.Content,
                    Date = m.Date,
                    HasAttachments = m.HasAttachments,
                    MailingListID = (int)m.MailingListID,
                    SenderID = (int)m.SenderID,
                    Subject = m.Subject
                });
            }
            return messages;
        }

In Service Reference configuration I checked the option "Generate asynchronous operations". How do I use the generated GetMessagesAsync()? In the net I found examples that use AsyncCallback, however I'm not familiar with that. Is there a way to use it in some friendly way like async and await keywords in .NET 4.5? If not, what should I do to invoke the method asynchronously?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you select 'Generate asynchrounous operations', you will get the 'old' behavior where you have to use callbacks.

If you want to use the new async/await syntax, you will have to select 'Generate task-based operations' (which is selected by default).

When using the default Wcf template, this will generate the following proxy code:

  public System.Threading.Tasks.Task<string> GetDataAsync(int value) {
      return base.Channel.GetDataAsync(value);
  }

As you can see, there are no more callbacks. Instead a Task<T> is returned.

You can use this proxy in the following way:

public static async Task Foo()
{
    using (ServiceReference1.Service1Client client = new ServiceReference1.Service1Client())
    {
        Task<string> t = client.GetDataAsync(1);
        string result = await t;
    }
}

You should mark the calling method with async and then use await when calling your service method.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...