using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms; namespace AsyncProgramDemo
{
public delegate void ProgressChangedEventHandler(ProgressChangedEventArgs e); public delegate void CalculatePrimeCompletedEventHandler(
object sender,
CalculatePrimeCompletedEventArgs e); public class PrimeNumberCalculator : Component
{
public event ProgressChangedEventHandler ProgressChanged;
public event CalculatePrimeCompletedEventHandler CalculatePrimeCompleted; private SendOrPostCallback onProgressReportDelegate;
private SendOrPostCallback onCompletedDelegate; protected virtual void InitializeDelegates()
{
onProgressReportDelegate =
new SendOrPostCallback(ReportProgress);
onCompletedDelegate =
new SendOrPostCallback(CalculateCompleted);
} private delegate void WorkerEventHandler(
int numberToCheck,
AsyncOperation asyncOp); private HybridDictionary userStateToLifetime =
new HybridDictionary(); public PrimeNumberCalculator()
{
//InitializeComponent(); InitializeDelegates();
} // This method is invoked via the AsyncOperation object,
// so it is guaranteed to be executed on the correct thread.
private void CalculateCompleted(object operationState)
{
CalculatePrimeCompletedEventArgs e =
operationState as CalculatePrimeCompletedEventArgs; OnCalculatePrimeCompleted(e);
} // This method is invoked via the AsyncOperation object,
// so it is guaranteed to be executed on the correct thread.
private void ReportProgress(object state)
{
ProgressChangedEventArgs e =
state as ProgressChangedEventArgs; OnProgressChanged(e);
} protected void OnCalculatePrimeCompleted(
CalculatePrimeCompletedEventArgs e)
{
if (CalculatePrimeCompleted != null)
{
CalculatePrimeCompleted(this, e);
}
} protected void OnProgressChanged(ProgressChangedEventArgs e)
{
if (ProgressChanged != null)
{
ProgressChanged(e);
}
} // This is the method that the underlying, free-threaded
// asynchronous behavior will invoke. This will happen on
// an arbitrary thread.
private void CompletionMethod(
int numberToTest,
int firstDivisor,
bool isPrime,
Exception exception,
bool canceled,
AsyncOperation asyncOp)
{
// If the task was not previously canceled,
// remove the task from the lifetime collection.
if (!canceled)
{
lock (userStateToLifetime.SyncRoot)
{
userStateToLifetime.Remove(asyncOp.UserSuppliedState);
}
} // Package the results of the operation in a
// CalculatePrimeCompletedEventArgs.
CalculatePrimeCompletedEventArgs e =
new CalculatePrimeCompletedEventArgs(
numberToTest,
firstDivisor,
isPrime,
exception,
canceled,
asyncOp.UserSuppliedState); // End the task. The asyncOp object is responsible
// for marshaling the call.
asyncOp.PostOperationCompleted(onCompletedDelegate, e); // Note that after the call to OperationCompleted,
// asyncOp is no longer usable, and any attempt to use it
// will cause an exception to be thrown.
} // Utility method for determining if a
// task has been canceled.
private bool TaskCanceled(object taskId)
{
return (userStateToLifetime[taskId] == null);
} // This method performs the actual prime number computation.
// It is executed on the worker thread.
private void CalculateWorker(
int numberToTest,
AsyncOperation asyncOp)
{
bool isPrime = false;
int firstDivisor = 1;
Exception e = null; // Check that the task is still active.
// The operation may have been canceled before
// the thread was scheduled.
if (!TaskCanceled(asyncOp.UserSuppliedState))
{
try
{
// Find all the prime numbers up to
// the square root of numberToTest.
ArrayList primes = BuildPrimeNumberList(
numberToTest,
asyncOp); // Now we have a list of primes less than
// numberToTest.
isPrime = IsPrime(
primes,
numberToTest,
out firstDivisor);
}
catch (Exception ex)
{
e = ex;
}
} //CalculatePrimeState calcState = new CalculatePrimeState(
// numberToTest,
// firstDivisor,
// isPrime,
// e,
// TaskCanceled(asyncOp.UserSuppliedState),
// asyncOp); //this.CompletionMethod(calcState); this.CompletionMethod(
numberToTest,
firstDivisor,
isPrime,
e,
TaskCanceled(asyncOp.UserSuppliedState),
asyncOp); //completionMethodDelegate(calcState);
} // This method computes the list of prime numbers used by the
// IsPrime method.
private ArrayList BuildPrimeNumberList(
int numberToTest,
AsyncOperation asyncOp)
{
ProgressChangedEventArgs e = null;
ArrayList primes = new ArrayList();
int firstDivisor;
int n = 5; // Add the first prime numbers.
primes.Add(2);
primes.Add(3); // Do the work.
while (n < numberToTest &&
!TaskCanceled(asyncOp.UserSuppliedState))
{
if (IsPrime(primes, n, out firstDivisor))
{
// Report to the client that a prime was found.
e = new CalculatePrimeProgressChangedEventArgs(
n,
(int)((float)n / (float)numberToTest * 100),
asyncOp.UserSuppliedState); asyncOp.Post(this.onProgressReportDelegate, e);
Thread.Sleep(1);
primes.Add(n); // Yield the rest of this time slice.
Thread.Sleep(0);
} // Skip even numbers.
n += 2;
} return primes;
} // This method tests n for primality against the list of
// prime numbers contained in the primes parameter.
private bool IsPrime(
ArrayList primes,
int n,
out int firstDivisor)
{
bool foundDivisor = false;
bool exceedsSquareRoot = false; int i = 0;
int divisor = 0;
firstDivisor = 1; // Stop the search if:
// there are no more primes in the list,
// there is a divisor of n in the list, or
// there is a prime that is larger than
// the square root of n.
while (
(i < primes.Count) &&
!foundDivisor &&
!exceedsSquareRoot)
{
// The divisor variable will be the smallest
// prime number not yet tried.
divisor = (int)primes[i++]; // Determine whether the divisor is greater
// than the square root of n.
if (divisor * divisor > n)
{
exceedsSquareRoot = true;
}
// Determine whether the divisor is a factor of n.
else if (n % divisor == 0)
{
firstDivisor = divisor;
foundDivisor = true;
}
} return !foundDivisor;
} // This method starts an asynchronous calculation.
// First, it checks the supplied task ID for uniqueness.
// If taskId is unique, it creates a new WorkerEventHandler
// and calls its BeginInvoke method to start the calculation.
public virtual void CalculatePrimeAsync(
int numberToTest,
object taskId)
{
// Create an AsyncOperation for taskId.
AsyncOperation asyncOp =
AsyncOperationManager.CreateOperation(taskId); // Multiple threads will access the task dictionary,
// so it must be locked to serialize access.
lock (userStateToLifetime.SyncRoot)
{
if (userStateToLifetime.Contains(taskId))
{
throw new ArgumentException(
"Task ID parameter must be unique",
"taskId");
} userStateToLifetime[taskId] = asyncOp;
} // Start the asynchronous operation.
WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);
workerDelegate.BeginInvoke(
numberToTest,
asyncOp,
null,
null);
} // This method cancels a pending asynchronous operation.
public void CancelAsync(object taskId)
{
AsyncOperation asyncOp = userStateToLifetime[taskId] as AsyncOperation;
if (asyncOp != null)
{
lock (userStateToLifetime.SyncRoot)
{
userStateToLifetime.Remove(taskId);
}
}
} } public class CalculatePrimeCompletedEventArgs :
AsyncCompletedEventArgs
{
private int numberToTestValue = 0;
private int firstDivisorValue = 1;
private bool isPrimeValue; public CalculatePrimeCompletedEventArgs(
int numberToTest,
int firstDivisor,
bool isPrime,
Exception e,
bool canceled,
object state)
: base(e, canceled, state)
{
this.numberToTestValue = numberToTest;
this.firstDivisorValue = firstDivisor;
this.isPrimeValue = isPrime;
} public int NumberToTest
{
get
{
// Raise an exception if the operation failed or
// was canceled.
RaiseExceptionIfNecessary(); // If the operation was successful, return the
// property value.
return numberToTestValue;
}
} public int FirstDivisor
{
get
{
// Raise an exception if the operation failed or
// was canceled.
RaiseExceptionIfNecessary(); // If the operation was successful, return the
// property value.
return firstDivisorValue;
}
} public bool IsPrime
{
get
{
// Raise an exception if the operation failed or
// was canceled.
RaiseExceptionIfNecessary(); // If the operation was successful, return the
// property value.
return isPrimeValue;
}
}
} public class CalculatePrimeProgressChangedEventArgs :
ProgressChangedEventArgs
{
private int latestPrimeNumberValue = 1; public CalculatePrimeProgressChangedEventArgs(
int latestPrime,
int progressPercentage,
object userToken)
: base(progressPercentage, userToken)
{
this.latestPrimeNumberValue = latestPrime;
} public int LatestPrimeNumber
{
get
{
return latestPrimeNumberValue;
}
}
} }

  

异步编程设计模式Demo - PrimeNumberCalculator的更多相关文章

  1. 异步编程设计模式Demo - AsyncComponentSample

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...

  2. 异步编程设计模式 - IronPythonDebugger

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsof ...

  3. [.net 多线程]异步编程模式

    .NET中的异步编程 - EAP/APM 从.NET 4.5开始,支持的三种异步编程模式: 基于事件的异步编程设计模式 (EAP,Event-based Asynchronous Pattern) 异 ...

  4. 【温故而知新-万花筒】C# 异步编程 逆变 协变 委托 事件 事件参数 迭代 线程、多线程、线程池、后台线程

    额基本脱离了2.0 3.5的时代了.在.net 4.0+ 时代.一切都是辣么简单! 参考文档: http://www.cnblogs.com/linzheng/archive/2012/04/11/2 ...

  5. .NET “底层”异步编程模式——异步编程模型(Asynchronous Programming Model,APM)

    本文内容 异步编程类型 异步编程模型(APM) 参考资料 首先澄清,异步编程模式(Asynchronous Programming Patterns)与异步编程模型(Asynchronous Prog ...

  6. C#秘密武器之异步编程

    一.概述 1.什么是异步? 异步操作通常用于执行完成时间可能较长的任务,如打开大文件.连接远程计算机或查询数据库.异步操作在主应用程序线程以外的线程中执行.应用程序调用方法异步执行某个操作时,应用程序 ...

  7. [.NET] 怎样使用 async & await 一步步将同步代码转换为异步编程

    怎样使用 async & await 一步步将同步代码转换为异步编程 [博主]反骨仔 [出处]http://www.cnblogs.com/liqingwen/p/6079707.html  ...

  8. 多线程之异步编程: 经典和最新的异步编程模型,async与await

    经典的异步编程模型(IAsyncResult) 最新的异步编程模型(async 和 await) 将 IAsyncInfo 转换成 Task 将 Task 转换成 IAsyncInfo 示例1.使用经 ...

  9. 多线程之异步编程: 经典和最新的异步编程模型, IAsyncInfo 与 Task 相互转换

    经典的异步编程模型(IAsyncResult) 最新的异步编程模型(async 和 await) 将 IAsyncInfo 转换成 Task 将 Task 转换成 IAsyncInfo 示例1.使用经 ...

随机推荐

  1. 2016年最受欢迎中国开源软件TOP 20

    开源软件对程序员来说是一个经常接触的软件,作为一个经常接触的软件,当然想知道自己用的软件受欢迎程度,基于此,开源中国在近日公布“2016年度最受欢迎中国开源软件评选”结果,在TOP20榜单中,前5名分 ...

  2. 解压和生成 system.img&data.img ( yaffs2格式)

    做为一名Android手机用户, 拿到system.img和data.img不是件难事 有这两个image可以做什么呢? ^_^可以做很多事,比如删除一些不想用的系统应用(/system/app目录下 ...

  3. list append 总是复制前面的参数,而不复制最后一个参数

    append 总是复制前面的参数,而不复制最后一个参数 (define a1 '(1 2 3)) (define a2 '(a b c)) (define x (append a1 a2)) x ; ...

  4. zoj2112

    题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2112 经典的动态区间第K大. 用树状数组套线段树. 对原数组建一个树 ...

  5. MapReduce流程、如何统计任务数目以及Partitioner

    核心功能描述 应用程序通常会通过提供map和reduce来实现 Mapper和Reducer接口,它们组成作业的核心. Map是一类将输入记录集转换为中间格式记录集的独立任务. 这种转换的中间格式记录 ...

  6. MySql按日期时间段进行统计(前一天、本周、某一天、某个时间段)

    在mysql数据库中,常常会遇到统计当天的内容.例如,在user表中,日期字段为:log_time 统计当天 sql语句为: select * from user where date(log_tim ...

  7. Oracle的sql语句中case关键字的用法 & 单双引号的使用

    关于sql中单引号和双引号的使用,来一点说明: 1. 查询列的别名如果含有汉字或者特殊字符(如以'_'开头),需要用双引号引起来.而且只能用双引号,单引号是不可以的. 2. 如果想让某列返回固定的值, ...

  8. 【转】Devexpress使用之:GridControl控件(合并表头)

    Devexpress系列控件功能很强大,使用起来也不太容易,我也是边摸索边使用,如果有时间我会把常用控件的使用方法整理出来的. using System; using System.Collectio ...

  9. Arcgis API for Android之GPS定位

    欢迎大家增加Arcgis API for Android的QQ交流群:337469080 先说说写这篇文章的原因吧,在群内讨论的过程中,有人提到了定位的问题,刚好,自己曾经在做相关工作的时候做过相关的 ...

  10. C#隐式执行CMD命令

    本文实现C#隐式执行CMD功能命令.下图是示例程序的主界面. 在命令文本框输入DOS命令,点击"Run"button.在以下的文本框中输出执行结果. 以下是程序的完整代码. 本程序 ...