Nirav Mehta

Hi freind,

I am facing problem in threading

eg:

int sum(int a, int b)

{

//complex code/

//time conusming code

return int;

}

Now I want to run this method through tread.. but here i have return type so confused how to your with threading




Re: Visual C# General Thread Problem

XRaheemX

I think you are wanting to use asynchronous threading so that you can have a callback. Try this example:

using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

class AsyncTest
{
  delegate string UrlFetcher(string url);
  
  public static void Main()
  {
    UrlFetcher u = new UrlFetcher (Fetch);
    u.BeginInvoke ("some url", 
            new AsyncCallback (AfterFetch),
            "this is state");
    // Just to demonstrate stuff going on while
    // the fetch happens...
    for (int i=0; i < 10; i++)
    {
      Console.WriteLine ("Foreground thread counter: {0}", i);
      Thread.Sleep(1000);
    }
  }
  
  static string Fetch (string url)
  {
    // Just to simulate it taking a while to fetch the
    // contents
    Thread.Sleep (5000);
    return "Contents of the url";
  }
  
  static void AfterFetch (IAsyncResult result)
  {
    Console.WriteLine ("Delegate completed.");
    Console.WriteLine (" State: {0}", result.AsyncState);
    AsyncResult async = (AsyncResult) result;
    UrlFetcher fetcher = (UrlFetcher) async.AsyncDelegate;
    Console.WriteLine (" Contents: {0}", fetcher.EndInvoke(result));
  }
} 





Re: Visual C# General Thread Problem

OmegaMan

 NiravMehta wrote:
Now I want to run this method through tread.. but here i have return type so confused how to your with threading


Here is an alternate method of threading. I have created a class that upon allocation will create a worker thread. The calling application can either call the class synchronously or asynchronously. That is done by commenting out the different areas below. The class has these attributes that may be gotchas if not implemented:
  1. Worker thread is a background thread so that it won't prevent the primary process from not terminating if it is shutdown.
  2. Handles the exception ThreadAbortException if thread.abort is called.
Here is the code which creates the thread example. Comment/uncomment out different areas to test the different ways of use.

using System.Threading;
...

ThreadMe op = new ThreadMe(5,6);

#region Synchronous
if (op.WaitForFinish() == false)
{
    Console.WriteLine("Operation timedout...cancelling");
    op.Cancel();
    Thread.Sleep(1000); // Give it time for the cancel.
}
else
{
    Console.WriteLine("Operation Succeeded Result ({0})", op.Result);
}
#endregion
#region Asynchronous
//do
//{
//    Thread.Sleep(1000);
//     // Simulate a cancel 
//     // op.Cancel();
//     // Thread.Sleep(1000); // Give it time to cancel.
//} while (op.IsDone() == false);
#endregion

Console.WriteLine("Result ({0})", op.Result);

Here is the thread class. Note it doesn't implement dispose and it should a proper dispose of the thread as well as more complex variables should always be done...it is not shown here for brevity. Note change the sleep time to simulate a timeout during an asynchronous call.

public class ThreadMe
{
    /// <summary>Simulates a threading operation. Allows for syncrhonous operation
    /// <see cref="WaitForFinish"/> and asynchronous operations <see cref="IsDone"/>.</summary>
    /// <remarks>A proper dispose was not implemented.</remarks>
    /// <param name="a">A value</param>
    /// <param name="b">B value</param>
    public ThreadMe(int a, int b)
    {
        _a = a;
        _b = b;
        worker = new Thread(doWork);
        // Background so not to not prevent the
        // process from terminating.
        worker.IsBackground = true; 
        worker.Start();
    }

    private void doWork()
    {

        try
        { // Simulate work
            Random rdm = new Random();
            Thread.Sleep(1000); // Change this to simulate timeout
            _Result = (int)(rdm.NextDouble() * _a) + (int)(rdm.NextDouble() * _b);
            Thread.Sleep(1000);
        }

        // Catch this if the parent calls thread.abort()
        // So we handle a cancel gracefully.
        catch (ThreadAbortException)
        {
            // We have handled the exception and will simply return without data.
            // Otherwise the abort will be rethrown out of this block.
            Thread.ResetAbort(); 
            _Result = -1;
        }
        finally
        {
            _isDone = true;
        }
    }

   #region Public Properties / Operations
    /// <summary>Wait for the thread to finish.</summary>
    /// <returns>True if finished normally, false if timeout</returns>
    public bool WaitForFinish()
    {
        return worker.Join(5000);
    }

    /// <summary>Optional method to check for operations done in an
    /// aschronous mode.</summary>
    /// <returns>True if thread is done or false if it is not.</returns>
    /// <remarks>Check value of the result if it is -1, then the operation
    /// was canceled.</remarks>
    public bool IsDone()
    {
        return _isDone;
    }

    /// <summary>Cancel thread operations here return -1.</summary>
    public void Cancel()
    { worker.Abort(); }

    /// <summary>Acquire result value here, check <see cref="IsDone"/> to 
    /// verify if work is done during asynchrous access.</summary>
    /// <remarks>-1 signals no operational work complete.</remarks>
    public int Result { 
        get           { return _Result; } 
        protected set { _Result = value; }}
#endregion

   #region Variables
    Thread worker;
    private int _Result;
    private int _a;
    private int _b;
    bool        _isDone;
#endregion
}






Re: Visual C# General Thread Problem

NiravMehta

Hi Brian,

thanks for this code but here my actual problem

i have client - server scenario.

when client hit save button. save method on server will execute and reruns nos of inserted rows.

Now same operation I want to achive through thread.

so when clients hit save button each save operation runs in seperate thread.

Here I have doubt, hot to pass, retrive data in threadStart Method in my case

my save method on server:

public Int save(obj a, obj b)

{

//save operation

returns noOfinsterted Rows;

}

On button click event

{

int I = ObjEmp.save(obj a, obj b);

}

but Through threading How to deal with this on button click

Regards,

Nirav






Re: Visual C# General Thread Problem

NiravMehta

Hi Friend,

thanks for this code but here my actual problem

i have client - server scenario.

when client hit save button. save method on server will execute and reruns nos of inserted rows.

Now same operation I want to achive through thread.

so when clients hit save button each save operation runs in seperate thread.

Here I have doubt, hot to pass, retrive data in threadStart Method in my case

my save method on server:

public Int save(obj a, obj b)

{

//save operation

returns noOfinsterted Rows;

}

On button click event

{

int I = ObjEmp.save(obj a, obj b);

}

but Through threading How to deal with this on button click

Regards,

Nirav