2016-12-08 19 views
0

ユーザーは任意のサイズの番号を入力できるC#コンソールアプリケーションを作成しました。その後、ユーザーがプログラムでどのように何を検索するかを選択できるようになりましたその数は、シングルコアまたはマルチコアを使用しています。シングルスレッドよりも時間がかかるマルチスレッド技術C#

プログラムは正常に動作しているようですが、両方のオプションを使用して10,000,000という正確な数値がマルチスレッドオプションの持続時間を長くするようです。誰かがこれにいくつかの光を当てることができます。

UPDATE

このに探していくつかの時間を過ごし、受け入れ答えに従った後、私が入力した番号を決定するためにプロセッサを押すカウンタ変数の反復中に集中的な計算を関与重要な変更を実施しました。この場合、マルチスレッディング操作によって速度が大幅に向上します。

改訂コードは、それがWPFアプリケーションに基づいた以下の通りである:

using System; 
using System.Windows; 
using System.Windows.Controls; 
using System.Threading; 
using System.Diagnostics; 
using System.ComponentModel; 
using System.Text.RegularExpressions; 

    namespace C_Sharp_Programming_Portfolio 
    { 
    public partial class Multithreading : Page 
    { 
     /* Variable declarations */ 
     static string numberTextToEncrypt; 
     static double numberDoubleToEncrypt; 
     static bool areaCodeCheck; 
     static int areaCodeLength; 
     static int noCores; 
     static double[] from = new Double[Environment.ProcessorCount]; 
     static double[] to = new Double[Environment.ProcessorCount]; 
     static string areaConfirmed; 
     static string completionTime; 
     static string coresUsed; 
     static string correctNumber; 
     static string numberTextToDecrypt; 
     Stopwatch watch = new Stopwatch(); 

     /* Stores the divisible number following dividing the telephone number by the number of cores */ 
     static double valuePerThread; 

     /* Stores the divisible number following dividing the telephone number by the number of cores, later 
     used for setting the values for each core to check telephone number entered*/ 
     static double difference; 

     /* Create two read only arrays and store area codes and region names */ 
     static readonly double[] areaCodes = { 0113, 0114, 0115, 0116, 0117, 0118, 01200, 01202, 01204, 01205, 01206, 01207, 01208, 01209, 0121, 01223, 01224, 01225, 01226, 01227, 01228, 01229,,,,,,, 01241, 01242, 01243, 01244, 01245, 01246, 01248, 01249, 01250, 01252, 01253, 01254, 01255, 01256, 01257, 01258, 01259, 01260, 01261, 01262, 01263, 01264, 01267, 01268, 01269, 01270, 01271, 01273, 01274, 01275, 01276, 01277, 01278, 01279, 01280, 01282, 01283, 01284, 01285, 01286, 01287, 01288, 01289, 01290, 01291, 01292, 01293, 01294, 01295, 01296, 01297, 01298, 01299, 01300, 01301, 01302, 01303, 01304, 01305, 01306, 01307, 01308, 01309, 0131, 01320, 01322, 01323, 01324, 01325, 01326, 01327, 01328, 01329, 01330, 01332, 01333, 01334, 01335, 01337, 01339, 01340, 01341, 01342, 01343, 01344, 01346, 01347, 01348, 01349, 01350, 01352, 01353, 01354, 01355, 01356, 01357, 01358, 01359, 01360, 01361, 01362, 01363, 01364, 01366, 01367, 01368, 01369, 01371, 01372, 01373, 01375, 01376, 01377, 01379, 01380, 01381, 01382, 01383, 01384, 01386, 01387, 013873, 01388, 01389, 01392, 01394, 01395, 01397, 01398, 01400, 01403, 01404, 01405, 01406, 01407, 01408, 01409, 0141, 01420, 01422, 01423, 01424, 01425, 01427, 01428, 01429, 01430, 01431, 01432, 01433, 01434, 01435, 01436, 01437, 01438, 01439, 01440, 01442, 01443, 01444, 01445, 01446, 01449, 01450, 01451, 01452, 01453, 01454, 01455, 01456, 01457, 01458, 01460, 01461, 01462, 01463, 01464, 01465, 01466, 01467, 01469, 01470, 01471, 01472, 01473, 01474, 01475, 01476, 01477, 01478, 01479, 01480, 01481, 01482, 01483, 01484, 01485, 01487, 01488, 01489, 01490, 01491, 01492, 01493, 01494, 01495, 01496, 01497, 01499, 01501, 01502, 01503, 01505, 01506, 01507, 01508, 01509, 0151, 01520, 01522, 01524, 015242, 01525, 01526, 01527, 01528, 01529, 01530, 01531, 01534, 01535, 01536, 01538, 01539, 015394, 015395, 015396, 01540, 01542, 01543, 01544, 01545, 01546, 01547, 01548, 01549, 01550, 01553, 01554, 01555, 01556, 01557, 01558, 01559, 01560, 01561, 01562, 01563, 01564, 01565, 01566, 01567, 01568, 01569, 01570, 01571, 01572, 01573, 01575, 01576, 01577, 01578, 01579, 01580, 01581, 01582, 01583, 01584, 01586, 01588, 01590, 01591, 01592, 01593, 01594, 01595, 01597, 01598, 01599, 01600, 01603, 01604, 01606, 01608, 01609, 0161, 01620, 01621, 01622, 01623, 01624, 01625, 01626, 01628, 01629, 01630, 01631, 01633, 01634, 01635, 01636, 01637, 01638, 01639, 01641, 01642, 01643, 01644, 01646, 01647, 01650, 01651, 01652, 01653, 01654, 01655, 01656, 01659, 01661, 01663, 01664, 01665, 01666, 01667, 01668, 01669, 01670, 01671, 01672, 01673, 01674, 01675, 01676, 01677, 01678, 01680, 01681, 01683, 01684, 01685, 01686, 01687, 01688, 01689, 01690, 01691, 01692, 01694, 01695, 01697, 016973, 016974, 016977, 01698, 01700, 01702, 01704, 01706, 01707, 01708, 01709, 01720, 01721, 01722, 01723, 01724, 01725, 01726, 01727, 01728, 01729, 01730, 01732, 01733, 01736, 01737, 01738, 01740, 01743, 01744, 01745, 01746, 01747, 01748, 01749, 01750, 01751, 01752, 01753, 01754, 01756, 01757, 01758, 01759, 01760, 01761, 01763, 01764, 01765, 01766, 01767, 01768, 017683, 017684, 017687, 01769, 01770, 01771, 01772, 01773, 01775, 01776, 01777, 01778, 01779, 01780, 01782, 01784, 01785, 01786, 01787, 01788, 01789, 01790, 01792, 01793, 01794, 01795, 01796, 01797, 01798, 01799, 01803, 01805, 01806, 01807, 01808, 01809, 01821, 01822, 01823, 01824, 01825, 01827, 01828, 01829, 01830, 01832, 01833, 01834, 01835, 01837, 01838, 01840, 01841, 01842, 01843, 01844, 01845, 01847, 01848, 01851, 01852, 01854, 01855, 01856, 01857, 01858, 01859, 01862, 01863, 01864, 01865, 01866, 01869, 01870, 01871, 01872, 01873, 01874, 01875, 01876, 01877, 01878, 01879, 01880, 01882, 01883, 01884, 01885, 01886, 01887, 01888, 01889, 01890, 01892, 01895, 01896, 01899, 01900, 01902, 01903, 01904, 01905, 01908, 01909, 0191, 01920, 01922, 01923, 01924, 01925, 01926, 01928, 01929, 01931, 01932, 01933, 01934, 01935, 01937, 01938, 01939, 01942, 01943, 01944, 01945, 01946, 019467, 01947, 01948, 01949, 01950, 01951, 01952, 01953, 01954, 01955, 01957, 01959, 01962, 01963, 01964, 01967, 01968, 01969, 01970, 01971, 01972, 01974, 01975, 01977, 01978, 01980, 01981, 01982, 01983, 01984, 01985, 01986, 01987, 01988, 01989, 01992, 01993, 01994, 01995, 01997, 020, 023, 024, 028, 029 }; 
     static readonly string[] regions = { "Leeds", "Sheffield", "Nottingham", "Leicester", "Bristol", "Reading", "Clitheroe", "Bournemouth", "Bolton", "Boston", "Colchester", "Consett", "Bodmin", "Redruth", "Birmingham", "Cambridge", "Aberdeen", "Bath", "Barnsley", "Canterbury", "Carlisle", "Barrow-in Furness/Millom", "Ashford (Kent)", "Bedford", "Abingdon", "Coatbridge", "Bideford", "Cardigan", "Arbroath", "Cheltenham", "Chichester", "Chester", "Chelmsford", "Chesterfield", "Bangor (Gwynedd)", "Chippenham", "Blairgowrie", "Aldershot", "Blackpool", "Blackburn", "Clacton-on-Sea", "Basingstoke", "Coppull", "Blandford", "Alloa", "Congleton", "Banff", "Bridlington", "Cromer", "Andover", "Carmarthen", "Basildon", "Ammanford", "Crewe", "Barnstaple", "Brighton", "Bradford", "Clevedon", "Camberley", "Brentwood", "Bridgwater", "Bishops Stortford", "Buckingham", "Burnley", "Burton-on-Trent", "Bury-St-Edmunds", "Cirencester", "Caernarfon", "Guisborough", "Bude", "Berwick-on-Tweed", "Cumnock", "Chepstow", "Ayr", "Crawley", "Ardrossan", "Banbury", "Aylesbury", "Axminster", "Buxton", "Bewdley", "Cerne Abbas", "Arrochar", "Doncaster", "Folkestone", "Dover", "Dorchester", "Dorking", "Forfar", "Bridport", "Forres", "Edinburgh", "Fort Augustus", "Dartford", "Eastbourne", "Falkirk", "Darlington", "Falmouth", "Daventry", "Fakenham", "Fareham", "Banchory", "Derby", "Anstruther", "St Andrews", "Ashbourne", "Ladybank", "Aboyne/Ballater", "Craigellachie", "Barmouth", "East Grinstead", "Elgin", "Bracknell", "Fraserburgh", "Easingwold", "Fishguard", "Dingwall", "Dunkeld", "Mold", "Ely", "Chatteris", "East Kilbride", "Brechin", "Strathaven", "Ellon", "Pakenham", "Killearn", "Duns", "Dereham", "Crediton", "Ashburton", "Downham Market", "Faringdon", "Dunbar", "Dunoon", "Great Dunmow", "Esher", "Frome", "Grays Thurrock", "Braintree", "Driffield", "Diss", "Devizes", "Fortrose", "Dundee", "Dunfermline", "Dudley", "Evesham", "Dumfries", "Langholm", "Bishop Auckland/Stanhope", "Dumbarton", "Exeter", "Felixstowe", "Budleigh Salterton", "Fort William", "Dulverton", "Honington", "Horsham", "Honiton", "Goole", "Holbeach", "Holyhead", "Golspie", "Holsworthy", "Glasgow", "Alton", "Halifax", "Boroughbridge/Harrogate", "Hastings", "Ringwood", "Gainsborough", "Haslemere", "Hartlepool", "Market Weighton/North Cave", "Helmsdale", "Hereford", "Hathersage", "Bellingham/Haltwhistle/Hexham", "Heathfield", "Helensburgh", "Clynderwen/Haverfordwest", "Stevenage", "Helmsley", "Haverhill", "Hemel Hempstead", "Pontypridd", "Haywards Heath", "Gairloch", "Barry", "Stowmarket", "Hawick", "Stow-on-the-Wold", "Gloucester", "Dursley", "Chipping Sodbury", "Hinckley", "Glenurquhart", "Glossop", "Glastonbury", "Chard", "Gretna", "Hitchin", "Inverness", "Insch", "Girvan", "Huntly", "Inverurie", "Killingholme", "Isle of Skye – Edinbane", "Isle of Skye – Broadford", "Grimsby", "Ipswich", "Gravesend", "Greenock", "Grantham", "Holmes Chapel", "Isle of Skye – Portree", "Grantown-on-Spey", "Huntingdon", "Guernsey", "Hull", "Guildford", "Huddersfield", "Hunstanton", "Warboys", "Hungerford", "Bishops Waltham", "Corwen", "Henley-on-Thames", "Colwyn Bay", "Great Yarmouth", "High Wycombe", "Pontypool", "Islay and Jura", "Hay-on-Wye", "Inveraray", "Harthill", "Lowestoft", "Looe", "Johnstone", "Bathgate", "Alford (Lincs)/Louth/Horncastle", "Brooke", "Loughborough", "Liverpool", "Lochcarron", "Lincoln", "Lancaster", "Hornby", "Leighton Buzzard", "Martin", "Redditch", "Laggan", "Sleaford", "Coalville", "Ledbury", "Jersey", "Keighley", "Kettering", "Leek", "Kendal", "Hawkshead", "Grange-Over-Sands", "Sedbergh", "Kingussie", "Keith", "Cannock", "Kington", "Llanarth", "Lochgilphead", "Knighton", "Kingsbridge", "Lairg", "Llandovery", "Kings Lynn", "Llanelli", "Lanark", "Castle Douglas", "Kirkcudbright", "Llandeilo", "Llandysul", "Moscow", "Laurencekirk", "Kidderminster", "Kilmarnock", "Lapworth", "Knutsford", "Launceston", "Killin", "Leominster", "Stonehaven", "Lampeter", "Lochinver", "Oakham", "Kelso", "Kirriemuir", "Lockerbie", "Kinross", "Lauder", "Liskeard", "Cranbrook", "New Luce", "Luton", "Carradale", "Ludlow", "Campbeltown", "Bishops Castle", "Lymington", "Llanwrtyd Wells", "Kirkcaldy", "Lybster", "Lydney", "Lerwick, Shetland Islands", "Llandrindod Wells", "Lynton", "Kyle", "Monmouth", "Norwich", "Northampton", "Northwich", "Chipping Norton", "Northallerton", "Manchester", "North Berwick", "Maldon", "Maidstone", "Mansfield", "Isle of Man", "Macclesfield", "Newton Abbot", "Maidenhead", "Matlock", "Market Drayton", "Oban", "Newport", "Medway", "Newbury", "Newark", "Newquay", "Newmarket", "Neath", "Strathy", "Middlesbrough", "Minehead", "New Galloway", "Milford Haven", "Moretonhampstead", "Cemmaes Road", "Oldmeldrum", "Brigg", "Malton", "Machynlleth", "Maybole", "Bridgend", "Sanquhar", "Prudhoe", "New Mills", "Melton Mowbray", "Alnwick", "Malmesbury", "Nairn", "Bamburgh", "Rothbury", "Morpeth", "Newton Stewart", "Marlborough", "Market Rasen", "Montrose", "Coleshill", "Meriden", "Bedale", "Bala", "Isle of Mull – Craignure", "Isle of Mull – Fionnphort", "Moffat", "Malvern", "Merthyr Tydfil", "Llanidloes/Newtown", "Mallaig", "Isle of Mull – Tobermory", "Orpington", "Betws-y-Coed", "Oswestry", "North Walsham", "Church Stretton", "Skelmersdale", "Brampton (6 figure numbers)", "Wigton", "Raughton Head", "Brampton (4 and 5 figure numbers)", "Motherwell", "Rothesay", "Southend-on-Sea", "Southport", "Rochdale", "Welwyn Garden City", "Romford", "Rotherham", "Isles of Scilly", "Peebles", "Salisbury", "Scarborough", "Scunthorpe", "Rockbourne", "St Austell", "St Albans", "Saxmundham", "Settle", "Petersfield", "Sevenoaks", "Peterborough", "Penzance", "Redhill", "Perth", "Sedgefield", "Shrewsbury", "St Helens", "Rhyl", "Bridgnorth", "Shaftesbury", "Richmond", "Shepton Mallet", "Selkirk", "Pickering", "Plymouth", "Slough", "Skegness", "Skipton", "Selby", "Pwllheli", "Pocklington", "Swaffham", "Temple Cloud", "Royston", "Crieff", "Ripon", "Porthmadog", "Sandy", "Penrith", "Appleby", "Pooley Bridge", "Keswick", "South Molton", "Isle of Arran", "Maud", "Preston", "Ripley", "Spalding", "Stranraer", "Retford", "Bourne", "Peterhead", "Stamford", "Stoke-on-Trent", "Staines", "Stafford", "Stirling", "Sudbury", "Rugby", "Stratford-upon-Avon", "Spilsby", "Swansea", "Swindon", "Romsey", "Sittingbourne", "Pitlochry", "Rye", "Pulborough", "Saffron Walden", "Torquay", "Torrington", "Sullom Voe, Shetland Islands", "Ballindalloch", "Tomatin", "Tomdoun", "Kinrossie", "Tavistock", "Taunton", "Ruthin", "Uckfield", "Tamworth", "Coupar Angus", "Tarporley", "Kirkwhelpington", "Clopton", "Barnard Castle", "Narberth", "St Boswells", "Okehampton", "Dalmally", "Camelford", "Padstow", "Thetford", "Thanet", "Thame", "Thirsk", "Thurso/Tongue", "Thornhill", "Lewis and Great Bernera, Outer Hebrides", "Kilmelford", "Ullapool", "Ballachulish", "Orkney", "Sanday", "Market Harborough", "Harris, Outer Hebrides", "Tain", "Ardgay", "Abington", "Oxford", "Kilchrenan", "Bicester", "Benebecula, Outer Hebrides", "Barra, Outer Hebrides", "Truro", "Abergavenny", "Brecon", "Tranent", "North Uist, Outer Hebrides", "Callander", "South Uist, Outer Hebrides", "Scarinish", "Tarbert", "Kinloch Rannoch", "Caterham", "Tiverton", "Bromyard", "Knightwick", "Aberfeldy", "Turriff", "Rugeley", "Ayton/Coldstream", "Tunbridge Wells", "Uxbridge", "Galashiels", "Biggar", "Workington", "Wolverhampton", "Worthing", "York", "Worcester", "Milton Keynes", "Worksop", "Tyneside/Durham/Sunderland", "Ware", "Walsall", "Watford", "Wakefield", "Warrington", "Warwick", "Runcorn", "Wareham", "Shap", "Weybridge", "Wellingborough", "Weston-Super-Mare", "Yeovil", "Wetherby", "Welshpool", "Wem", "Wigan", "Guiseley", "West Heslerton", "Wisbech", "Whitehaven", "Gosforth", "Whitby", "Whitchurch", "Whatton", "Sandwick, Shetland Islands", "Colonsay", "Telford", "Wymondham", "Madingley", "Wick", "Mid Yell, Shetland Islands", "Westerham", "Winchester", "Wincanton", "Hornsea/Patrington", "Strontian", "Penicuik", "Leyburn", "Aberystwyth", "Scourie", "Glenborrodale", "Llanon", "Alford (Aberdeen)/Strathdon", "Pontefract", "Wrexham", "Amesbury", "Wormbridge", "Builth Wells", "Isle of Wight", "Watchet", "Warminster", "Bungay", "Ebbsfleet", "Wigtown", "Ross-on-Wye", "Lea Valley", "Witney", "St Clears", "Garstang", "Strathpeffer", "London", "Southampton/Portsmouth", "Coventry", "Northern Ireland", "Cardiff" }; 

     /* Set up the Multithreading class */ 
     public Multithreading() 
     { 
      /* Set up Multithreading component */ 
      InitializeComponent(); 
     } 

     /* Button function to encrypt the telephone number entered */ 
     void ButtonEncrypt(object sender, RoutedEventArgs e) 
     { 
      numberTextToEncrypt = null; 
      numberDoubleToEncrypt = 0; // Set variable to zero 
      areaCodeCheck = false; // Set variable to false 
      NumberFound.Text = "#"; // Reset text block value 
      Region.Text = "#"; // Reset text block value 
      EncryptionTime.Text = "#"; // Set text block value 
      CoresUsed.Text = "#"; // Set text block value 
      NumberEncryptionTextBox.Text = null; // Set text block value to null 
      numberTextToEncrypt = NumberToEncrypt.Text; // Set variable equal to text box text 
      numberTextToEncrypt = Regex.Replace(numberTextToEncrypt, @"\s+", ""); // Remove white space entered 
      /* Check if variable length is equal to 11 digits */ 
      if (numberTextToEncrypt.Length == 11) 
      { 
       /* Try to convert the variable to double */ 
       if (double.TryParse(numberTextToEncrypt, out numberDoubleToEncrypt)) 
       { 
        /* Invoke function to verify the area code entered matches an area */ 
        verifyAreaCode(); 
        /* Check the area code entered matches an area */ 
        if (areaCodeCheck) 
        { 
         watch.Reset(); // Reset stopwatch 
         watch.Start(); // Start stopwatch 
         progressBarValueEncrypt.IsIndeterminate = true; // Invoke progress bar 
         NumberFound.Text = "[PROCESSING]"; // Set text block value 
         EncryptionTime.Text = "[PROCESSING]"; // Set text block value 
         CoresUsed.Text = "[PROCESSING]"; // Set text block value 
         Region.Text = "[PROCESSING]"; // Set text block value 
         BackgroundWorker inBackground = new BackgroundWorker(); // Create background worker method 
         inBackground.DoWork += doWork; // Invoke 'doWork' method 
         inBackground.RunWorkerCompleted += onCompletion; // Invoke 'onCompletion' method once work is completed 
         inBackground.RunWorkerAsync(); // Run background worker asynchronously 
        } 
        else 
        { 
         /* Display error message and return command to the user interface */ 
         MessageBox.Show("Please ensure a valid UK area code is entered", "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
         return; 
        } 
       } 
       else 
       { 
        /* Display error message and return command to the user interface */ 
        MessageBox.Show("Please ensure only a number is entered", "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
        return; 
       } 
      } 
      else 
      { 
       /* Display error message and return command to the user interface */ 
       MessageBox.Show("Please ensure a valid telephone number is entered containing 11 digits", "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
       return; 
      } 

     } 

     /* Function to carry out work in background worker thread */ 
     void doWork(object sender, DoWorkEventArgs e) 
     { 
      valuePerThread = 0; // Initialise the variable to zero 
      difference = 0; // Initialise the variable to zero 
      areaCodeCheck = false; // Initialise variable to false 
      areaCodeLength = 0; // Set area code length to zero 
      noCores = Environment.ProcessorCount; // Get number of cores and store in variable 
      Thread[] multiThreads = new Thread[noCores]; // Create array of threads equal to number of cores 

      /* Check to see if the telephone number is divisible by the number of cores */ 
      if (numberDoubleToEncrypt % noCores == 0) 
      { 
       /* Divide the telephone number entered by the number of cores and store in variable */ 
       valuePerThread = numberDoubleToEncrypt/noCores; 

       /* Divide the telephone number entered by the number of cores and store in new variable, 
       in order to determine the increment value to be added */ 
       difference = numberDoubleToEncrypt/noCores; 

       /* Invoke function to set the values to be checked on each core to determine the telephone 
       number the user has entered */ 
       setValues(); 
      } 
      else 
      { 
       /* Divide the telephone number entered by the number of cores and round up to the nearest 
       whole number, followed by storing the value in a variable */ 
       valuePerThread = Math.Ceiling(numberDoubleToEncrypt/noCores); 

       /* Divide the telephone number entered by the number of cores and round up to the nearest 
       whole number, followed by storing the value in a new variable in order to determine the 
       increment value to be added */ 
       difference = Math.Ceiling(numberDoubleToEncrypt/noCores); 

       /* Invoke function to set the values to be checked on each core to determine the telephone 
       number the user has entered */ 
       setValues(); 
      } 

      /* For the number of cores in the device, execute the following */ 
      for (int i = 0; i < noCores; i++) 
      { 
       multiThreads[i] = new Thread(findNumber); // Create a new thread and pass in the 'findNumber' function as a parameter 
       multiThreads[i].Start(i); // Invoke the thread and pass in the position to the 'findNumber' function 
      } 

      /* For the number of cores in the device, wait for each thread to complete its process before 
      continuing */ 
      for (int i = 0; i < noCores; i++) multiThreads[i].Join(); 

      /* Store the time taken to complete the process in a variable */ 
      completionTime = Math.Floor(watch.Elapsed.TotalSeconds).ToString() + " seconds "; 
      coresUsed = noCores.ToString(); // Convert the cores used to a string and store in a variable 
     } 

     /* Function to set the 'from' and 'to' array position values for each core on the device to determine 
     the telephone number the user entered */ 
     void setValues() 
     { 
      double start = 0; // Declare and initialise the 'start' value to zero 
      /* For the number of cores on the device, execute the for loop */ 
      for (int i = 0; i < noCores; i++) 
      { 
       from[i] = start; // Store the 'start' value in the 'from' array position 
       to[i] = valuePerThread; // Store the 'valuePerThread' value in the 'to' array position 
       start += difference; // Increment the 'start' value by the difference 
       valuePerThread += difference; // Increment the 'valuePerThread' by the difference 
      } 
     } 

     /* Function to execute from the background worker once the 'doWork' function is completed */ 
     void onCompletion(object sender, RunWorkerCompletedEventArgs e) 
     { 
      /* Set text block value and insert a space at the position proceeding the area code length */ 
      NumberFound.Text = correctNumber.Insert(areaCodeLength, " "); 
      Region.Text = areaConfirmed; // Set text block value 
      EncryptionTime.Text = completionTime; // Set text block value 
      CoresUsed.Text = coresUsed; // Set text block value 
      /* Call external class method and pass in variable to encrypt the telephone number entered. 
      Set text box text equal to encrypted value */ 
      NumberEncryptionTextBox.Text = EncryptionDecryption.Encrypt(correctNumber); 
      progressBarValueEncrypt.IsIndeterminate = false; // Disable the progress bar 
     } 

     /* Function to verify the area code matches an area code */ 
     void verifyAreaCode() 
     { 
      /* For the length of the 'areaCodes', execute the following loop */ 
      for (int j = 0; j < areaCodes.Length; j++) 
      { 
       /* Check if the first four characters of the number to encrypt text matches 
       the array position of the area code */ 
       if (numberTextToEncrypt.Substring(1, 4) == Convert.ToString(areaCodes[j])) 
       { 
        areaCodeCheck = true; // Set the variable to true to confirm it matches 
       } 
       else 
       { 
        /* Check if the first three characters of the number to encrypt text matches 
        the array position of the area code */ 
        if (numberTextToEncrypt.Substring(1, 3) == Convert.ToString(areaCodes[j])) 
        { 
         areaCodeCheck = true; // Set the variable to true to confirm it matches 
        } 
        else 
        { 
         /* Check if the first two characters of the number to encrypt text matches 
         the array position of the area code */ 
         if (numberTextToEncrypt.Substring(1, 2) == Convert.ToString(areaCodes[j])) 
         { 
          areaCodeCheck = true; // Set the variable to true to confirm it matches 
         } 
        } 
       } 
      } 
     } 

     /* Function to find the telephone number entered by the user, passing int the position from the 
     calling thread */ 
     void findNumber(object value) 
     { 
      /* Declare and initialise the variable set to the position of the calling thread by casting the 
      object to an integer */ 
      int position = (int)value; 
      /* Declare and initialise member double value to the 'from' array 'position' value */ 
      double i = from[position]; 
      /* Execute while loop to determine if the telephone number entered matches a number between 
      the array 'from' position value to the 'to' position value */ 
      while (i >= from[position] && i <= to[position]) 
      { 
       /* Check if the value matches the telephone number */ 
       if (i == numberDoubleToEncrypt) 
       { 
        /* Set the variable equal to the matching value; convert to string; add a '0' and store 
        in variable */ 
        correctNumber = "0" + i.ToString(); 
        /* Invoke the find region function and pass in the 'correctNumber' value */ 
        findRegion(correctNumber); 
        return; // Return the command to the user interface 
       } 
       i++; // Increment by one 
      } 
      return; // Return the command to the user interface 
     } 

     /* Function to find the region from the telephone number found by the computer */ 
     void findRegion(string confirmedNumber) 
     { 
      /* For the length of the 'areaCodes', execute the following loop */ 
      for (int i = 0; i < areaCodes.Length; i++) 
      { 
       /* Check if the first four characters of the number to encrypt text matches 
       the array position of the area code */ 
       if (confirmedNumber.Substring(1, 4) == Convert.ToString(areaCodes[i])) 
       { 
        areaConfirmed = regions[i]; // Set variable value equal to the 'regions' array position value 
        areaCodeLength = 5; // Set variable value 
       } 
       else 
       { 
        /* Check if the first three characters of the number to encrypt text matches 
        the array position of the area code */ 
        if (confirmedNumber.Substring(1, 3) == Convert.ToString(areaCodes[i])) 
        { 
         areaConfirmed = regions[i]; // Set variable value equal to the 'regions' array position value 
         areaCodeLength = 4; // Set variable value 
        } 
        else 
        { 
         /* Check if the first two characters of the number to encrypt text matches 
         the array position of the area code */ 
         if (confirmedNumber.Substring(1, 2) == Convert.ToString(areaCodes[i])) 
         { 
          areaConfirmed = regions[i]; // Set variable value equal to the 'regions' array position value 
          areaCodeLength = 3; // Set variable value 
         } 
        } 
       } 
      } 
     } 

     } 
    } 
+2

開始スレッドにはコストがかかります。それぞれのスレッドが行う作業が軽い場合、スレッドを開始するオーバーヘッドは、最初に得ることのできるすべての利益を邪魔します。各スレッドの作業を増やしてください。 – Jens

+0

さて、おそらく私の場合、システムをプッシュするためにいくつかの余分な数字を追加すると思います。私の現在のコードの実装には既存のエラーはありますか? –

+2

while(counter!= convertInput){if(counter == convertInput) ':' if'条件は常に 'false'です。 – AlexD

答えて

1

余分性能で開始するスレッドを起動するオーバーヘッドによって置換されている複数のスレッドを使用してからでした。この実装は、より複雑な命令でより役に立ちます。

これはあまりにも速く実行されすぎて、マルチスレッドの恩恵を受けません。

while (counter != convertInput) 
{ 
    if (counter == convertInput) 
    { 
     watch.Stop(); 
     return; 
    } 
    counter++; 
} 
+0

メッセージをありがとう - 私はちょうど上記のコードを編集しました。しかし、上記のメッセージは、ユーザーの実際の入力に完全に依存しています。私の場合、ユーザーは10,000,000などの大きな数値を入力します。これはもちろん比較的速いですが、これ以上の数字を入力すると、1つのスレッドでもっと速くなるようです。 –

+0

これはまだ非常に速い命令であり、マルチスレッド化のメリットはありません。たとえば、重複したテキストファイルを検索するプログラムがありました。これらのファイルは時には数百メガバイトのサイズでしたが、小さなテキストファイルを与えると実際には複数のスレッドを使用するのが遅くなりました。 –

+0

私はいくつかのテストを行いました。この場合のマルチスレッド技術は、少なくとも11桁の数字が入力されたときに有益であることに気付きました。この値は1,000,000,000,0の値が21秒で完了します。しかし、同じ値は1つのスレッドで1分12秒かかります。明らかに、CPUを絞るために実装できるどちらのテストシナリオに対しても、何らかのさらなる指示を行う方が良いでしょう。 –

関連する問題