使用Task.Factory

时间:2019-05-28 06:56:47

标签: c# multithreading asynchronous events task

这是负责connect到服务器和get一些细节的代码。

public class MigrationManager
{
       private string referenceServerId;

       public void MigrateAnalyzer(string serverid)
       {
            Gw _Gw = new Gw() // library reference
           _Gw.onConnectSucceeded += Handle_OnConnectSucceeded;
           _Gw.onConnectFailed += Handle_OnConnectFailed;

           ConnectToServer(prxHA, serverid);
       }

       private void ConnectToServer(string sid)
       {            
          workstationIDForReference = anayzer;
          string credentials = GWServiceCredentials("somesecret");
           referenceServerId = sid;
         _Gw.connectToServer("SSL", "device1-mydomain.net", credentials, referenceServerId);
       }

     }

此连接操作可能会在两种情况下结束。

  • 连接成功
  • 连接失败

这些事件的处理如下所示

private void Handle_OnConnectFailed(int hr)
{
      string msg = $"{referenceServerId}";
      Console.WriteLine("Connecting to server {0} is failed", msg); 
}

private void Handle_OnConnectSucceeded()
{
     Console.WriteLine("Connecting to server is success");
}

这很好。现在,我将其更改为支持多线程。因为存在多个连接到服务器的请求。

List<string> requestCollection = new List<string>();
requestCollection.Add("I3-1");
requestCollection.Add("I3-2");
requestCollection.Add("I3-3");

var taskList = new List<Task>();

foreach (var serverid in requestCollection )
{
     MigrationManager manager = new MigrationManager();
     var task = Task.Factory.StartNew(() => manager.MigrateAnalyzer(serverid.ToString()));
}

Task.WaitAll(taskList.ToArray());

我在下面看到输出

Console.WriteLine("Connecting to server I3-1 is failed");
Console.WriteLine("Connecting to server I3-2 is failed");
Console.WriteLine("Connecting to server I3-3 is failed");

输出看起来不错!

但是,我认为COM将使用共享资源。那我怎么用“锁”呢?

0 个答案:

没有答案