0 votes
by (360 points)
edited

I'm trying to save an attachment I get from a byte[] from a webservice. The problem is that my code continues even before the completed event of the method could have been called. Is there some way to let the application wait for that event.

This is the part where I save the attachment as byes:

var temporaryStream = new MemoryStream();
foreach (var attachment in msg.Attachments.Where(attachment =>  
     attachment.FileName.Equals(attachmentName)))
{
     attachment.Save(temporaryStream);
}
return temporaryStream.ToArray();

And this is how I try to get the byte[]:

byte[] result = null;
try
{
    _popClient.SaveAttachmentCompleted += (sender, e) =>
               {
                   if (e.Error != null) return;
                   result = e.Result;
               };
    _popClient.SaveAttachmentAsync(uniqueId, attachmentName);
    return result;
 }

The Async call takes to long to finish... Is there any way to speed the process of fetching the attachment up or another way to fix that problem?

Applies to: Rebex Secure Mail

1 Answer

0 votes
by (148k points)
edited
 
Best answer

I assume your webservice offers a synchronous SaveAttachment method that returns byte[], but your Silverlight application sees SaveAttachmentAsync method and SaveAtachmentCompleted event instead. Is this correct?

This is Microsoft's Event-based Asynchronous Pattern and the right solution would be to rewrite your application a bit (see the links for more info) to take advantage of it.

Basically, what you need are two methods on your application's form - one that starts the operation (and does not return anything), and another that handles the SaveAttachmentCompleted event (which would get called when the operation is done).

Speeding up the process of attachment fetching would not help. The SaveAttachmentAsync method finishes instantly, even sooner than the webservice itself is actually called. The whole webservice call operation occurs in the background. This issue is not actually related to Rebex, it's just the way event-vased asyncrhonous pattern in works. If you replaced the SaveAttachment method in your webservice with a simple "return new byte[0]", chances are you would still get identical behavior.

...