共通コードの2:BackgroundWorkerまたはTaskを使用してコードを非同期で実行します.
3304 ワード
まずSystem.ComponentModelを参照
using System.ComponentModel;
次にbackgroundworkerを作成します
.net 4.0パラレルライブラリのtaskを使用すると、より簡単になり、一段落してパフォーマンスが向上します.
using System.ComponentModel;
次にbackgroundworkerを作成します
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TestArgs args = (TestArgs)e.Argument;
MyMethod(args.Content, args.Index);
}
/// <summary>
/// backgroundWorker1_DoWork
/// </summary>
protected class TestArgs
{
public string Content { set; get; }
public int Index { set; get; }
public TestArgss(string content, int index)
{
Content = content;
Index = index;
}
}
public void BulkFillJson(string content, int index)
{
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
TestArgsargs = new TestArgs(content, index);
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerAsync(args);
}
.net 4.0パラレルライブラリのtaskを使用すると、より簡単になり、一段落してパフォーマンスが向上します.
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
MyMethod(content, index);
});