PC Review Forums Newsgroups Microsoft DotNet Microsoft Dot NET Compact Framework Re: Async calls

Reply

Re: Async calls

 
Thread Tools Rate Thread
Old 08-07-2003, 10:27 PM   #1
Ilya Tumanov [MS]
Guest
 
Posts: n/a
Default Re: Async calls


Eli,

Take a look at the sample below.

Best regards,

Ilya

using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Threading;
using System.Text;

namespace beginWrite
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
//
// button1
//
this.button1.Location = new System.Drawing.Point(88, 44);
this.button1.Text = "button1";
this.button1.Click += new
System.EventHandler(this.button1_Click);
//
// Form1
//
this.Controls.Add(this.button1);
this.Text = "Form1";

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>

static void Main()
{
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e)
{
SuperFileStream stream = new SuperFileStream ("MyFile.txt",
FileMode.OpenOrCreate);

Encoding en = new UnicodeEncoding(false, false);

byte [] bytes = en.GetBytes ("Hello, world!");

IAsyncResult result = stream.BeginWrite ( bytes, 0,
bytes.Length, new AsyncCallback( WriteDone), 1 );

MessageBox.Show("Write started, waiting for completion...");

stream.EndWrite(result);

stream.Close();
}

public void WriteDone( IAsyncResult ar ) {
MessageBox.Show("Write completed, caller #" + ar.AsyncState);
}

}

public class SuperFileStream : FileStream {

// Add more constructors...

public SuperFileStream (String path, FileMode mode) : base (path,
mode) {

}

public override IAsyncResult BeginWrite(byte[] buffer, int offset,
int count, AsyncCallback callback, Object state)
{
IOAsyncResult result = new IOAsyncResult();

result.BeginWrite(this, buffer, offset, count, callback, state);

return(IAsyncResult)result;
}

public override void EndWrite(IAsyncResult asyncResult)
{
IOAsyncResult result = (IOAsyncResult)asyncResult;

result.EndWrite();
}
}


internal class IOAsyncResult : IAsyncResult
{
internal Stream stream; // Stream to write to

internal ManualResetEvent waitHandle; // Flip this as soon as
we're done
internal Object state; // Keep state object
here
internal bool isCompleted; // Done flag

internal byte[] buffer; // Stuff to write to
the stream
internal int offset;
internal int count;

internal AsyncCallback callback; // Call this after
we're done

internal Thread asyncThread; // Thread in which work
is done

internal IOAsyncResult()
{
waitHandle = new ManualResetEvent(false);
isCompleted = false;
}

public bool IsCompleted {
get { return isCompleted; }
}

public WaitHandle AsyncWaitHandle {
get { return waitHandle; }
}

public Object AsyncState {
get { return state; }
}

public bool CompletedSynchronously {
get { return false; }
}

internal void BeginWrite(Stream stream, byte[] buffer, int offset,
int count, AsyncCallback callback, Object state) {
this.buffer = buffer; // Memorize all we
need to write to a file
this.offset = offset;
this.count = count;
this.stream = stream;

this.callback = callback; // Store callback
and state
this.state = state;

this.asyncThread = new Thread( new
ThreadStart(this.AsyncThread));
this.asyncThread.Start(); // Start a new
thread to write to a file
}

internal void AsyncThread() { // Worker thread
try {
lock (stream) { // Do not allow
others to use our stream

// Add code to compensate for changed file position

stream.Write(buffer, offset, count);
// Write to the
stream using normal
// blocking method.
}
}
catch (Exception) {
// Add exception handling here.
}
finally {
this.isCompleted = true; // We're done
this.waitHandle.Set();
}

try {
this.callback(this); // Execute
callback, watch for exceptions
}
catch (Exception) {
// Add exception handling here
}
}

internal void EndWrite() {
this.waitHandle.WaitOne();
}

}
}

This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
>Content-Class: urn:content-classes:message
>From: "Eli Markov" <nada@nada.com>
>Sender: "Eli Markov" <nada@nada.com>
>References: <0aa401c33af7$b073d460$a101280a@phx.gbl>

<ORouDPwODHA.2316@TK2MSFTNGP11.phx.gbl>
>Subject: Re: Async calls
>Date: Wed, 25 Jun 2003 09:25:10 -0700
>Lines: 91
>Message-ID: <022601c33b36$58ca1fa0$a101280a@phx.gbl>
>MIME-Version: 1.0
>Content-Type: text/plain;
> charset="iso-8859-1"
>Content-Transfer-Encoding: 7bit
>X-Newsreader: Microsoft CDO for Windows 2000
>X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
>Thread-Index: AcM7NljKvd83DFqLRDmFFoiiOSyN+A==
>Newsgroups: microsoft.public.dotnet.framework.compactframework
>Path: cpmsftngxa06.phx.gbl
>Xref: cpmsftngxa06.phx.gbl

microsoft.public.dotnet.framework.compactframework:26606
>NNTP-Posting-Host: TK2MSFTNGXA09 10.40.1.161
>X-Tomcat-NG: microsoft.public.dotnet.framework.compactframework
>
>
>Thanks Neil,
>
>But I'm not sure what exactly to do inside the BeginMethod
>and the EndMethod. Lets say in the BeginMethod I start a
>thread which just sleeps for n seconds, when it complets
>how do I call the callback?
>
>If there is a sample, can you please point me to it.
>
>Regards Eli.
>
>>-----Original Message-----
>>I do it like this: define your own async interface, e.g.
>>
>>public interface IAsyncClass
>>{
>> object Method();
>> IAsyncResult BeginMethod(AsyncCallback callback,

>object state);
>> object EndMethod(IAsyncResult asyncResult);
>>}
>>
>>and then implement this in your class.
>>
>>For example, you have a class called StockNews. The

>interface would be
>>defined as follows:
>>
>>public interface IAsyncStockNews
>>{
>> string GetStockNews();
>> IAsyncResult BeginGetStockNews(AsyncCallback

>callback, object state);
>> string EndGetStockNews(IAsyncResult asyncResult);
>>}
>>
>>And then the StockNews class would implement this and

>looking something like
>>the following:
>>
>>public class StockNews : IAsyncStockNews
>>{
>> public StockNews()
>> {
>> // .ctor code here
>> }
>>
>> public string GetStockNews()
>> {
>> // TODO: Add StockNews.GetStockNews implementation
>> }
>>
>> public IAsyncResult BeginGetStockNews(AsyncCallback,

>object state)
>> {
>> // TODO: Add StockNews.BeginGetStockNews

>implementation
>> return null;
>> }
>>
>> public string EndGetStockNews(IASyncResult

>asyncResult)
>> {
>> // TODO: Add StockNews.EndGetStockNews

>implemenation
>> }
>>}
>>
>>--
>> Neil Cowburn
>> Microsoft Windows Embedded MVP
>> Content Master Ltd
>>
>> www.contentmaster.com
>>
>> Blog: http://blog.opennetcf.org/ncowburn/
>>
>>
>>
>>"Eli Markov" <nada@nada.com> wrote in message
>>news:0aa401c33af7$b073d460$a101280a@phx.gbl...
>>> Hi,
>>>
>>> Is there a way to implement BeginMethod EndMethod in a
>>> class to support asynchronious calls like in sockets and
>>> WS. If yes, any samples?

>>
>>
>>.
>>

>


  Reply With Quote
Reply



Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off