开发者

Calculate time of method execution and send to WCF service async

I need to implement time calculation for repository methods in my asp .net mvc project classes. The problem is that i need to send time calculation data to WCF Service which is time consuming. I think about threads which can help to cal WCF service asynchronously. But I have very little experience with it. Do I need to create new thread each time or I can create a global thread, if so then how? I have something like that:

StopWatch class

public class StopWatch
{
    private DateTime _startTime;
    private DateTime _endTime;

    public void Start()
    {
        _startTime = DateTime.Now;
 开发者_开发问答   }
    protected void StopTimerAndWriteStatistics()
    {
        _endTime = DateTime.Now;
        TimeSpan timeResult = _endTime - _startTime;
        //WCF proxy object
        var reporting = AppServerUtility.GetProxy<IReporting>();
        //Send data to server
        reporting.WriteStatistics(_startTime, _endTime, timeResult, "some information");
    }

    public void Stop()
    {
        //Here is the thread I have question with
        var thread = new Thread(StopTimerAndWriteStatistics);
        thread.Start();
    }
}

Using of StopWatch class in Repository

public class SomeRepository
{
    public List<ObjectInfo> List()
    {
        StopWatch sw = new StopWatch();
        sw.Start();
        //performing long time operation
        sw.Stop();
    }
}

What am I doing wrong with threads? How I can reuse thread for performance reason?


Your code seems fine. Once you've finished the long running operation you are spawning a new thread and perform the call to the web service in this thread. This seems a good approach to me. Another possibility is to use the BeginXXX and EndXXX methods generated by the web service proxy (/async option of svcutil.exe).


Why not using the .NET ThreadPool, with the QueueUserWorkItem method? You won't have to worry about starting the thread, you just queue it and your done.

You'd just call something like

ThreadPool.QueueUserWorkItem(new WaitCallback(StopTimerAndWriteStatistics));

Or you could even use a lambda expression and get rid of the StopTimerAndWriteStatistics method. (Haven't tested this one)

ThreadPool.QueueUserWorkItem(() => {
    _endTime = DateTime.Now;
    TimeSpan timeResult = _endTime - _startTime;
    //WCF proxy object
    var reporting = AppServerUtility.GetProxy<IReporting>();
    //Send data to server
    reporting.WriteStatistics(_startTime, _endTime, timeResult, "some information");
                                    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜